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
use crate::core::parser::segments;
use crate::core::parser::segments::base::Segment;
use crate::core::templaters::base::TemplatedFile;

type PredicateType = Option<fn(&dyn Segment) -> bool>;

#[derive(Debug, Default, Clone)]
pub struct Segments {
    base: Vec<Box<dyn Segment>>,
    templated_file: Option<TemplatedFile>,
}

impl Segments {
    pub fn iter(&self) -> impl Iterator<Item = &Box<dyn Segment>> {
        self.base.iter()
    }

    pub fn iterate_segments(&self) -> impl Iterator<Item = Segments> + '_ {
        let mut iter = self.base.iter();

        std::iter::from_fn(move || {
            let Some(segment) = iter.next() else {
                return None;
            };

            Segments::new(segment.clone(), self.templated_file.clone()).into()
        })
    }

    pub fn from_vec(base: Vec<Box<dyn Segment>>, templated_file: Option<TemplatedFile>) -> Self {
        Self { base, templated_file }
    }

    pub fn reversed(&self) -> Self {
        let mut base = self.base.clone();
        base.reverse();

        Self { base, templated_file: self.templated_file.clone() }
    }

    pub fn get(&self, index: usize, default: Option<Box<dyn Segment>>) -> Option<Box<dyn Segment>> {
        self.base.get(index).cloned().or(default)
    }

    pub fn first(&self) -> Option<&dyn Segment> {
        self.base.first().map(Box::as_ref)
    }

    pub fn last(&self) -> Option<&dyn Segment> {
        self.base.last().map(Box::as_ref)
    }

    #[track_caller]
    pub fn pop(&mut self) -> Box<dyn Segment> {
        self.base.pop().unwrap()
    }

    pub fn all(&self, predicate: PredicateType) -> bool {
        self.base.iter().all(|s| predicate.map_or(true, |pred| pred(s.as_ref())))
    }

    pub fn len(&self) -> usize {
        self.base.len()
    }

    pub fn is_empty(&self) -> bool {
        self.base.is_empty()
    }

    pub fn new(segment: Box<dyn Segment>, templated_file: Option<TemplatedFile>) -> Self {
        Self { base: vec![segment], templated_file }
    }

    pub fn children(&self, predicate: PredicateType) -> Segments {
        let mut child_segments = Vec::new();

        for s in &self.base {
            for child in s.get_segments() {
                if let Some(ref pred) = predicate {
                    if pred(child.as_ref()) {
                        child_segments.push(child);
                    }
                } else {
                    child_segments.push(child);
                }
            }
        }

        Segments { base: child_segments, templated_file: self.templated_file.clone() }
    }

    pub fn find_last(&self, predicate: PredicateType) -> Segments {
        self.base
            .iter()
            .rev()
            .find_map(|s| {
                if predicate.as_ref().map_or(true, |p| p(s.as_ref())) {
                    Some(Segments {
                        base: vec![s.clone()],
                        templated_file: self.templated_file.clone(),
                    })
                } else {
                    None
                }
            })
            .unwrap_or_else(|| Segments {
                base: vec![],
                templated_file: self.templated_file.clone(),
            })
    }

    pub fn find(&self, value: &dyn Segment) -> Option<usize> {
        self.index(value)
    }

    pub fn find_first<F: Fn(&dyn Segment) -> bool>(&self, predicate: Option<F>) -> Segments {
        for s in &self.base {
            if predicate.as_ref().map_or(true, |p| p(s.as_ref())) {
                return Segments {
                    base: vec![s.clone()],
                    templated_file: self.templated_file.clone(),
                };
            }
        }

        Segments { base: vec![], templated_file: self.templated_file.clone() }
    }

    pub fn index(&self, value: &dyn Segment) -> Option<usize> {
        self.base.iter().position(|it| it.dyn_eq(value))
    }

    #[track_caller]
    pub fn select(
        &self,
        select_if: PredicateType,
        loop_while: PredicateType,
        start_seg: Option<&dyn Segment>,
        stop_seg: Option<&dyn Segment>,
    ) -> Segments {
        let start_index = start_seg
            .and_then(|seg| self.base.iter().position(|x| x.dyn_eq(seg)))
            .map_or(0, |index| index + 1);

        let stop_index = stop_seg
            .and_then(|seg| self.base.iter().position(|x| x.dyn_eq(seg)))
            .unwrap_or_else(|| self.base.len());

        let mut buff = Vec::new();

        for seg in self.base.iter().skip(start_index).take(stop_index - start_index) {
            if let Some(loop_while) = &loop_while {
                if !loop_while(seg.as_ref()) {
                    break;
                }
            }

            if select_if.as_ref().map_or(true, |f| f(seg.as_ref())) {
                buff.push(seg.clone());
            }
        }

        Segments { base: buff, templated_file: self.templated_file.clone() }
    }
}

impl<I: std::slice::SliceIndex<[Box<dyn Segment>]>> std::ops::Index<I> for Segments {
    type Output = I::Output;

    fn index(&self, index: I) -> &Self::Output {
        &self.base[index]
    }
}

impl IntoIterator for Segments {
    type Item = Box<dyn Segment>;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.base.into_iter()
    }
}