1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
use log::trace;
use snafu::{ResultExt, Snafu};
use std::fmt::Debug;
use std::ops::Add;

use crate::html::{HtmlContent, HtmlTag};
use crate::pipeline::PipelineError;
use crate::{CssSelectorList, Pipeline};

#[derive(Debug, Snafu)]
pub enum CommandError {
    #[snafu(display("Failed run WITHOUT"))]
    WithoutFailed {
        #[snafu(backtrace)]
        source: WithoutError,
    },
    SubpipelineFailed {
        #[snafu(backtrace)]
        #[snafu(source(from(PipelineError, Box::new)))]
        source: Box<PipelineError>,
    },
}

#[derive(Debug, Snafu)]
pub enum WithoutError {
    #[snafu(display("Failed to remove HTML node"))]
    RemovingNodeFailed {
        #[snafu(backtrace)]
        source: crate::html::IndexError,
    },
}

/// Is the value directly defined or is it a sub-pipeline?
#[derive(Debug, PartialEq, Clone)]
pub enum ValueSource {
    StringValue(String),
}

impl ValueSource {
    pub(crate) fn render(&self) -> String {
        match self {
            ValueSource::StringValue(value) => value.clone(),
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum Command<'a> {
    /// Find all nodes, beginning at the input, that match the given CSS selector
    /// and return only those
    Only(CssSelectorList<'a>),
    /// Find all nodes, beginning at the input, that match the given CSS selector
    /// and remove them from their parent nodes.
    /// Returns the input as result.
    Without(CssSelectorList<'a>),
    /// runs a sub-pipeline on each element matching the given CSS selector
    /// Returns the input as result.
    ForEach(CssSelectorList<'a>, Pipeline<'a>),
    /// runs a sub-pipeline and replaces each element matching the given CSS selector with the result of the pipeline
    /// Returns the input as result.
    Replace(CssSelectorList<'a>, Pipeline<'a>),
    /// Remove the given attribute from all currently selected nodes
    /// Returns the input as result.
    ClearAttribute(String),
    /// Remove all children of the currently selected nodes
    /// Returns the input as result
    ClearContent,
    /// Add or Reset a given attribute with a new value
    /// Returns the input as result.
    SetAttribute(String, ValueSource),
    /// Remove all children of the currently selected nodes and add a new text as child instead
    /// Returns the input as result.
    SetTextContent(ValueSource),
    /// adds a new text as child
    /// Returns the input as result.
    AddTextContent(ValueSource),
    /// adds a new comment as child
    /// Returns the input as result.
    AddComment(ValueSource),
    /// runs a sub-pipeline and adds the result as child
    /// Returns the input as result.
    AddElement(Pipeline<'a>),
    /// creates an HTML element of given type
    /// Returns the created element as result.
    CreateElement(String),
}

impl<'a> Command<'a> {
    /// perform the action defined by the command on the set of nodes
    /// and return the calculated results.
    /// For some command the output can be equal to the input,
    /// others change the result-set
    pub(crate) fn execute(
        &self,
        input: &Vec<rctree::Node<HtmlContent>>,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        match self {
            Command::Only(selector) => Self::only(input, selector),
            Command::Without(selector) => {
                Self::without(input, selector).context(WithoutFailedSnafu)
            }
            Command::ClearAttribute(attribute) => Self::clear_attr(input, attribute),
            Command::ClearContent => Self::clear_content(input),
            Command::SetAttribute(attribute, value_source) => {
                Self::set_attr(input, attribute, value_source)
            }
            Command::SetTextContent(value_source) => Self::set_text_content(input, value_source),
            Command::AddTextContent(value_source) => Self::add_text_content(input, value_source),
            Command::AddComment(value_source) => Self::add_comment(input, value_source),
            Command::ForEach(selector, pipeline) => Self::for_each(input, selector, pipeline),
            Command::AddElement(pipeline) => Self::add_element(input, pipeline),
            Command::CreateElement(element_name) => Self::create_element(element_name),
            Command::Replace(selector, pipeline) => Self::replace(input, selector, pipeline),
        }
    }

    fn for_each(
        input: &Vec<rctree::Node<HtmlContent>>,
        selector: &CssSelectorList<'a>,
        pipeline: &Pipeline,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        let queried_elements = selector.query(input);
        let _ = pipeline.run_on(queried_elements);

        Ok(input.clone())
    }

    fn only(
        input: &Vec<rctree::Node<HtmlContent>>,
        selector: &CssSelectorList<'a>,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!("Running ONLY command using selector: {:#?}", selector);
        Ok(selector.query(input))
    }

    fn without(
        input: &Vec<rctree::Node<HtmlContent>>,
        selector: &CssSelectorList<'a>,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, WithoutError> {
        trace!("Running WITHOUT command using selector: {:#?}", selector);
        let findings = selector.query(input);

        for mut node in findings {
            node.detach();
        }

        Ok(input.clone())
    }

    fn replace(
        input: &Vec<rctree::Node<HtmlContent>>,
        selector: &CssSelectorList<'a>,
        pipeline: &Pipeline,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        let queried_elements = selector.query(input);
        let mut created_elements = pipeline.run_on(vec![]).context(SubpipelineFailedSnafu)?;

        for mut element_for_replacement in queried_elements {
            for new_element in &mut created_elements {
                let copy = new_element.make_deep_copy();
                element_for_replacement.insert_after(copy);
            }
            element_for_replacement.detach();
        }

        Ok(input.clone())
    }

    fn clear_attr(
        input: &Vec<rctree::Node<HtmlContent>>,
        attribute: &String,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!("Running CLEAR-ATTR command for attr: {:#?}", attribute);

        for node in input {
            let mut working_copy = rctree::Node::clone(node);
            let mut data = working_copy.borrow_mut();
            data.clear_attribute(attribute);
        }

        Ok(input.clone())
    }

    fn clear_content(
        input: &Vec<rctree::Node<HtmlContent>>,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!("Running CLEAR-CONTENT command");

        for node in input {
            for mut child in node.children() {
                child.detach()
            }
        }

        Ok(input.clone())
    }

    fn set_attr(
        input: &Vec<rctree::Node<HtmlContent>>,
        attribute: &String,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running SET-ATTR command for attr: {:#?} with value: {:#?}",
            attribute,
            value_source
        );

        for node in input {
            let mut working_copy = rctree::Node::clone(node);
            let mut data = working_copy.borrow_mut();
            data.set_attribute(attribute, value_source);
        }

        Ok(input.clone())
    }

    fn set_text_content(
        input: &Vec<rctree::Node<HtmlContent>>,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running SET-TEXT-CONTENT command with value: {:#?}",
            value_source
        );

        for node in input {
            // first clear everything that was there before
            for mut child in node.children() {
                child.detach()
            }

            let mut working_copy = rctree::Node::clone(node);
            working_copy.append(rctree::Node::new(HtmlContent::Text(value_source.render())));
        }

        Ok(input.clone())
    }

    fn add_text_content(
        input: &Vec<rctree::Node<HtmlContent>>,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running ADD-TEXT-CONTENT command with value: {:#?}",
            value_source
        );

        for node in input {
            let mut working_copy = rctree::Node::clone(node);
            working_copy.append(rctree::Node::new(HtmlContent::Text(value_source.render())));
        }

        Ok(input.clone())
    }

    fn add_comment(
        input: &Vec<rctree::Node<HtmlContent>>,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running ADD-COMMENT command with value: {:#?}",
            value_source
        );

        for node in input {
            let mut working_copy = rctree::Node::clone(node);
            working_copy.append(rctree::Node::new(HtmlContent::Comment(
                value_source.render(),
            )));
        }

        Ok(input.clone())
    }

    fn add_element(
        input: &Vec<rctree::Node<HtmlContent>>,
        pipeline: &Pipeline,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        for node in input {
            if let Some(new_element) = pipeline
                .run_on(vec![])
                .context(SubpipelineFailedSnafu)?
                .pop()
            {
                let mut working_copy = rctree::Node::clone(node);
                working_copy.append(new_element);
            }
        }

        Ok(input.clone())
    }

    fn create_element(name: &String) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        Ok(vec![rctree::Node::new(HtmlContent::Tag(HtmlTag::of_name(
            name.clone(),
        )))])
    }
}

impl<'a> Add<Command<'a>> for Command<'a> {
    type Output = Vec<Command<'a>>;

    fn add(self, rhs: Command<'a>) -> Self::Output {
        vec![self, rhs]
    }
}

impl<'a> Add<Option<Vec<Command<'a>>>> for Command<'a> {
    type Output = Vec<Command<'a>>;

    fn add(self, rhs: Option<Vec<Command<'a>>>) -> Self::Output {
        if let Some(mut vec) = rhs {
            vec.insert(0, self);
            return vec;
        }

        vec![self]
    }
}