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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Home of the LoadingBar methods and its associated structs and enums.
use colored::{Color, Colorize};
use crossterm::cursor::{RestorePosition, SavePosition};

use std::collections::HashMap;
use std::fmt;
use std::io::stdout;

use crossterm::{
    cursor::MoveTo,
    execute,
    style::Print,
    terminal::{Clear, ClearType},
};

pub enum LoadingBarOptions {
    Color(Option<Color>),
    Number(u16),
    Float(f32),
    Pos(u16, u16),
    Character(char),
    None,
}

impl LoadingBarOptions {
    fn get_color(&self) -> Option<Color> {
        match self {
            LoadingBarOptions::Color(color) => *color,
            _ => None,
        }
    }

    fn get_number(&self) -> u16 {
        match self {
            LoadingBarOptions::Number(number) => *number,
            _ => 0,
        }
    }

    fn get_float(&self) -> f32 {
        match self {
            LoadingBarOptions::Float(float) => *float,
            _ => 0.0,
        }
    }

    fn get_pos(&self) -> (u16, u16) {
        match self {
            LoadingBarOptions::Pos(x, y) => (*x, *y),
            _ => (0, 0),
        }
    }
    fn get_character(&self) -> char {
        match self {
            LoadingBarOptions::Character(character) => *character,
            _ => ' ',
        }
    }
}

#[derive(Debug, Clone)]
pub struct LoadingBar {
    pub(super) len: u16,
    pub(super) index: u16,
    pub(super) done: bool,
    pub(super) color: Option<colored::Color>,
    pub(super) space_left: u16,
    pub(super) half: bool,
    start_pos: (u16, u16),
    pub(super) character: char,
    pub(super) last_character: char,
    pub(super) bracket_color: Option<colored::Color>,
}

/// # These methods are for basic loading bar creation and manipulation.
impl LoadingBar {
    /// this is used to create a new loading bar
    /// # Arguments Len: Length of the loading bar
    /// # Arguments Color: Color of the loading bar, if None, it will be white
    /// # Arguments Pos: Position of the loading bar in the terminal using (x, y)
    pub fn new(len: u16, color: Option<colored::Color>, start_pos: (u16, u16)) -> LoadingBar {
        LoadingBar {
            len,
            index: 0,
            done: false,
            color,
            space_left: len,
            half: false,
            start_pos,
            character: '\u{2589}',
            last_character: '\u{258c}',
            bracket_color: None,
        }
    }

    /// this is used to change the position of the loading bar in the terminal using (x, y)
    /// # Arguments Pos: Position of the loading bar in the terminal using (x, y)
    /// it will cleear the old position and move to the new position (but not print anything)
    pub fn change_pos(&mut self, pos: (u16, u16)) {
        // clear the old bar
        let (x, y) = self.start_pos;
        execute!(stdout(), SavePosition).expect("\x07could not save cursor position\x07");
        execute!(stdout(), MoveTo(x, y)).expect("\x07could not move cursor\x07");
        execute!(stdout(), Clear(ClearType::UntilNewLine)).expect("\x07could not clear line\x07");
        execute!(stdout(), RestorePosition).expect("\x07could not restore cursor position\x07");
        self.start_pos = pos;
    }

    /// this is the same as change_pos but it also prints the the loading bar
    pub fn change_pos_print(&mut self, pos: (u16, u16)) {
        self.change_pos(pos);
        self.print();
    }

    pub fn advance(&mut self) {
        self.adv_index(1);
    }

    pub fn advance_print(&mut self) {
        self.adv_index_print(1);
    }

    pub fn advance_by(&mut self, index: u16) {
        self.adv_index(index);
    }

    pub fn advance_by_print(&mut self, index: u16) {
        self.adv_index_print(index);
    }

    pub fn change_character_type(&mut self, character: char) {
        self.character = character;
    }

    pub fn change_last_character(&mut self, character: char) {
        self.last_character = character;
    }

    pub fn change_bracket_color(&mut self, color: Option<colored::Color>) {
        self.bracket_color = color;
    }

    pub fn change_bracket_color_print(&mut self, color: Option<colored::Color>) {
        self.change_bracket_color(color);
        self.print();
    }

    pub fn change_last_character_print(&mut self, character: char) {
        self.change_last_character(character);
        self.print();
    }

    pub fn change_character_type_print(&mut self, character: char) {
        self.change_character_type(character);
        self.print();
    }

    pub fn advance_by_percent(&mut self, percentage: f32) {
        if percentage > 100.0 {
            panic!("\x07percentage must be between 0 and 100\x07");
        }
        let index = (self.len as f32 * percentage / 100.0) as u16;
        let reminder = (self.len as f32 * percentage % 100.0) as u16;
        if self.half {
            match reminder {
                0 => {
                    self.adv_index(index);
                }
                _ => {
                    self.adv_index(index + 1);
                    self.half = false;
                }
            }
        } else {
            match reminder {
                0 => {
                    self.adv_index(index);
                }
                _ => {
                    self.adv_index(index);
                    self.half = true;
                }
            }
        }
    }

    pub fn advance_by_percent_print(&mut self, percentage: f32) {
        self.advance_by_percent(percentage);
        self.goline_clear_print()
    }

    pub fn change_color(&mut self, color: Option<colored::Color>) {
        self.color = color;
    }

    pub fn change_color_print(&mut self, color: Option<colored::Color>) {
        self.change_color(color);
        self.goline_clear_print()
    }

    fn adv_index(&mut self, adv_val: u16) {
        if self.index + adv_val <= self.len {
            self.index += adv_val;
            self.done = false;
            self.space_left = self.len - self.index;
            if self.space_left == 0 {
                self.done = true;
            }
        } else {
            panic!("\x07 You can't advance more than the length of the bar\x07");
        }
    }

    pub fn change(&mut self, map: HashMap<&str, LoadingBarOptions>, print: bool) {
        for (key, value) in map {
            match key {
                "color" => {
                    self.color = value.get_color();
                    self.bracket_color = value.get_color();
                }
                "pos" => {
                    self.change_pos(value.get_pos());
                }
                "advance" => {
                    self.advance();
                }
                "advance_by" => {
                    self.advance_by(value.get_number());
                }
                "advance_by_percent" => {
                    self.advance_by_percent(value.get_float());
                }
                "last_character" => {
                    self.change_last_character(value.get_character());
                }
                "character_type" => {
                    self.change_character_type(value.get_character());
                }
                "bracket_color" => {
                    self.change_bracket_color(value.get_color());
                }
                "change_bar_color" => {
                    self.change_color(value.get_color());
                }
                _ => {
                    panic!("\x07{} is not a valid option\x07", key);
                }
            }
        }
        if print {
            self.print()
        }
    }

    fn adv_index_print(&mut self, add_val: u16) {
        self.adv_index(add_val);
        self.goline_clear_print();
    }

    fn goline_clear_print(&self) {
        let (x, y) = self.start_pos;
        execute!(stdout(), SavePosition).expect("\x07could not save cursor position\x07");
        execute!(stdout(), MoveTo(x, y)).expect("\x07could not move cursor\x07");
        execute!(stdout(), Clear(ClearType::UntilNewLine)).expect("\x07could not clear line\x07");
        execute!(stdout(), Print(&self)).expect("\x07could not print\x07");
        execute!(stdout(), RestorePosition).expect("\x07failed to restore cursor\x07");
    }

    pub fn print(&self) {
        self.goline_clear_print();
    }
}

impl fmt::Display for LoadingBar {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut bar = String::new();
        for _ in 0..self.index {
            bar.push('\u{2589}');
        }
        if self.half {
            bar.push('\u{258c}');
        }
        for _ in self.index..self.len {
            bar.push(' ');
        }
        write!(
            f,
            "[{}]",
            bar.color(self.color.unwrap_or(colored::Color::White)) // if we have a color, use it, otherwise use white
        )
    }
}

mod auto_run {
    use super::LoadingBar;
    use crate::{Color, Types};
    use std::{collections::HashMap, fmt, marker, thread, time::Duration};

    /// # these methods/functions are used to auomatically generate and or update the loading bar
    /// Note: because I don't fully understand threads and mutexes, you can't acces the loading bar once it's been used in one of these methods.
    impl LoadingBar {
        pub fn auto_run(
            time_in_seconds: u16,
            len: u16,
            start: u16,
            color: Option<colored::Color>,
            start_pos: (u16, u16),
        ) {
            if start >= len {
                println!();
                panic!("\x07start must be less than len\x07");
            }
            // find the amount of time that has per incremen
            let self_clone = LoadingBar {
                len,
                index: start,
                done: false,
                color,
                space_left: len - start,
                half: false,
                start_pos,
                character: '\u{2589}',
                last_character: '\u{258c}',
                bracket_color: None,
            };
            LoadingBar::auto_run_from(self_clone, time_in_seconds)
        }

        pub fn auto_run_change(
            change: Vec<Option<Color>>,
            time_in_seconds: u16,
            len: u16,
            start: u16,
            start_pos: (u16, u16),
        ) {
            if start >= len {
                println!();
                panic!("\x07start must be less than len\x07");
            }
            let mut self_clone = LoadingBar::new(len, change[0], start_pos);
            self_clone.advance_by(start);
            LoadingBar::auto_run_from_change(self_clone, change, time_in_seconds)
        }

        pub fn auto_run_from(mut loading_bar: LoadingBar, time_in_seconds: u16) {
            let index = time_in_seconds as f32 / (loading_bar.space_left + 1) as f32;
            loading_bar.print();
            thread::spawn(move || {
                for _ in 0..(loading_bar.space_left) {
                    loading_bar.advance_print();
                    thread::sleep(Duration::from_secs_f32(index));
                }
            });
        }
        pub fn auto_run_change_points(
            change: HashMap<u16, Option<Color>>,
            time_in_seconds: u16,
            len: u16,
            start: u16,
            start_pos: (u16, u16),
        ) {
            if start >= len {
                println!();
                panic!("\x07start must be less than len\x07");
            }
            let mut self_clone = LoadingBar::new(len, None, start_pos);
            self_clone.advance_by(start);
            LoadingBar::auto_run_from_change_points(
                self_clone,
                change,
                time_in_seconds,
                Types::Index,
            )
        }

        pub fn auto_run_from_change(
            loading_bar: LoadingBar,
            change: Vec<Option<Color>>,
            time_in_seconds: u16,
        ) {
            let change_len = change.len() as u16;
            crate::get_indexes(change_len, loading_bar.space_left + 1, loading_bar.len);
            let change_color = crate::get_index_and_value(
                change_len,
                loading_bar.space_left + 1,
                loading_bar.len,
                &change,
            );
            LoadingBar::auto_run_from_change_points(
                loading_bar,
                change_color,
                time_in_seconds,
                Types::Index,
            )
        }

        // TODO: make a similar function in TextLoadingBar and each one respective non from function
        pub fn auto_run_from_change_points<T, U>(
            mut loading_bar: LoadingBar,
            change: HashMap<T, U>,
            time_in_seconds: u16,
            type_change: Types,
        ) where
            T: Copy + fmt::Debug,
            u16: From<T>,
            f32: From<T>,
            U: Copy + fmt::Debug + marker::Send + 'static,
            Option<Color>: From<U>,
        {
            let index = time_in_seconds as f32 / (loading_bar.space_left + 1) as f32;
            let mut total = loading_bar.len - (loading_bar.space_left);
            let new_hash = crate::generic_to_u16(loading_bar.len, change, type_change);
            loading_bar.print();
            thread::spawn(move || {
                for _ in 0..(loading_bar.space_left) {
                    total += 1;
                    if new_hash.contains_key(&total) {
                        loading_bar.color = Option::<Color>::from(new_hash[&total]);
                    }

                    loading_bar.advance();
                    thread::sleep(Duration::from_secs_f32(index));
                    loading_bar.print()
                }
            });
        }
    }
}

mod change_at {
    use super::LoadingBar;
    impl LoadingBar {
        // TODO: implement change at type functions
    }
}