ask 0.0.11

A toolset for nicely displayed Questions and Answers through the terminal.
Documentation
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
pub struct Ask<T>{
    questions: Vec<T>
}

impl <T>Ask<T>
    where T : question::TraitQuestion {
    pub fn new()->Ask<T> {
        Ask{
            questions: vec!()
        }
    }

    pub fn question(&mut self, question_obj:T){
        self.questions.push(question_obj);
    }

    pub fn all(&mut self){
        for question in &mut self.questions {
            &question.send();
        }
    }
}

pub mod validate{
    pub mod group_options{
        use crate::question::AnswerCollection;
        
        pub fn selections_are_gtoe(answer_collection:& AnswerCollection, num : u16)->bool{
            let mut total_selected_answers = 0;
            for answer_set in & answer_collection.answer_sets{
                total_selected_answers += answer_set.answers.len() as u16;
            }
            total_selected_answers >= num
        }

        pub fn selections_are_ltoe(answer_collection:& AnswerCollection,  num : u16)->bool{
            let mut total_selected_answers = 0;
            for answer_set in & answer_collection.answer_sets{
                total_selected_answers += answer_set.answers.len() as u16;
            }
            total_selected_answers <= num
        }
    }
}

pub mod question{

    use std::io::{Write, stdout, Stdout, stdin};
    use termion::{input::TermRead, event::Key, cursor::DetectCursorPos};
    use termion::raw::IntoRawMode;
    use regex::Regex;


    // impl TraitQuestion for Confirm{
    //     fn send(&mut self)->Result<AnswerCollection, String>{

    //     }
    // }

    pub struct QuestionOption{
        name     : String,
        selected : bool,
    }

    impl QuestionOption{
        pub fn new(name :String)->QuestionOption{
            QuestionOption{
                name     : name,
                selected : false,
            }
        }

        pub fn toggle_selected(mut self, switch : Option<bool>)->Self{
            self.selected = if let Some(tf) = switch { tf }else{ !self.selected };
            self
        }
    }

    pub struct OptionGroup{
        name                 : &'static str,
        options              : Vec<QuestionOption>,
        options_len          : u16,
    }

    impl OptionGroup {
        pub fn new(group_name : &'static str) -> OptionGroup{
            OptionGroup{
                name             : group_name,
                options          : vec!(),
                options_len      : 0,
            }
        }

        // fn toggle_selected_option(&mut self, selector_index: usize, io : Option<bool>){
        //     if let Some(_io) = io{
        //         self.options_selected[selector_index] = _io;
        //     }else{
        //         self.options_selected[selector_index] = !self.options_selected[selector_index];
        //     }
        // }

        fn to_answerset(&self)-> AnswerSet{
            AnswerSet{
                group_name : self.name,
                answers    : self.get_all_selected_options()
            }
        }

        fn get_all_selected_options(&self)->Vec<String>{
            let mut i = 0;
            let mut result = vec!();
            for option in &self.options{
                if option.selected {
                    result.push(option.name.clone());
                }
                i += 1;
            }

            return result;
        }


        fn get_all_selected_indexies(&self)->Vec<usize>{
            let mut i = 0;
            let mut result = vec!();
            for options in &self.options{
                if options.selected {
                    result.push(i);
                }
                i += 1;
            }

            return result;
        }

        fn render_options(&self, stdout: &mut termion::raw::RawTerminal<Stdout>, selector_index: u16, size : (u16, u16)){
            let mut i = 0;


            for option in &self.options{
                let selector_str = if i == selector_index {
                    let selector = vec!(0xE2, 0x98, 0x9B);
                    String::from_utf8_lossy(&selector).into_owned()
                }else{
                    " ".to_owned()
                };

                let selected_icon = if self.options[i as usize].selected {
                    let large_filled_circle = vec!(0xE2, 0xAC, 0xA4);
                    String::from_utf8_lossy(&large_filled_circle).into_owned()
                }else{
                    let large_circle = vec!(0xE2, 0x97, 0xAF);
                    String::from_utf8_lossy(&large_circle).into_owned()
                };
                write!(stdout, "{}{}{}{}   {}  {}", termion::cursor::Goto(0,size.1 - self.options_len + i), termion::clear::CurrentLine, termion::clear::CurrentLine, selector_str, selected_icon, option.name );
                i += 1;
            }

            let selector_str = if i == selector_index {
                let selector = vec!(0xE2, 0x98, 0x9B);
                String::from_utf8_lossy(&selector).into_owned()
            }else{
                " ".to_owned()
            };
            // let continue_str = if self.can_continue(){"> Continue >"}else{"[ Continue ]"};
            let continue_str = "CONTINUE";
            write!(stdout, "{}{}{}   {}", termion::cursor::Goto(0,size.1 - self.options_len + i), termion::clear::CurrentLine, selector_str, continue_str );

            stdout.flush().unwrap();
        }

        // fn can_continue(& self)->bool{
        //     //is between min and max . if min and max are both 0 then just continue
        //     return if self.any_amount(){
        //         true
        //     }else if  self.get_selection_count() >= self.min_selections &&
        //                 self.get_selection_count() <= self.max_selections{
        //         true
        //     }else{
        //         false
        //     }
        // }

        // fn any_amount(& self)->bool{
        //     //is between min and max . if min and max are both 0 then just continue
        //     return if self.min_selections == 0 && self.max_selections == 0{
        //         true
        //     }else{
        //         false
        //     }
        // }

        //=== Accessors ===
        pub fn add_option_by_str(mut self, option:String)->Self{
            self.options.push(QuestionOption::new(option));
            self.options_len += 1;
            self
        }

        pub fn add_option(mut self, option: QuestionOption)->Self{
            self.options.push(option);
            self.options_len += 1;
            self
        }

        // pub fn max_selections(mut self, number:u16)->Self{
        //     self.max_selections = number;
        //     self
        // }

        // pub fn min_selections(mut self, number:u16)->Self{
        //     self.min_selections = number;
        //     self
        // }

    }

    pub trait TraitQuestion{
        fn send(&mut self)->Result<AnswerCollection, String>;
    }

    pub struct MultipleChoice{
        message            : String,
        prepended_message  : Option<String>,
        option_groups      : Vec<OptionGroup>,
        validate_fn        : Box<Fn(AnswerCollection)->bool>,
        cursor             : Cursor,
        continue_btn       : ContinueBtn,
        on_select_continue : bool, //as soo as all selection are vaid
    }

    struct Cursor{
        on_group  : u16,
        on_option : u16,
    }

    impl TraitQuestion for MultipleChoice{
        fn send(&mut self)->Result<AnswerCollection, String>{

            let mut stdout  = stdout().into_raw_mode().unwrap();
            let mut size    = termion::terminal_size().unwrap();

            //write out question
            write!(stdout, "{}{}",  self.prepended_message.as_ref().unwrap_or(&"".to_owned()), self.message);

            stdout.flush().unwrap();

            let (mut answer_collection, mut line_count) = self.render_options(size);

            let stdin = stdin();
            for c in stdin.keys(){
                size = termion::terminal_size().unwrap();
                match c.unwrap(){
                    // Key::Char('\n') => {
                    //     write!(stdout, "{}{}",
                    //     termion::scroll::Up(1),
                    //     termion::cursor::Goto(0,term_size.1),
                    //     ).unwrap();
                    // },
                    Key::Down => {
                        //move to next option if no more options move to next group, option 0,
                        //if no more groups move to first if cursor wrap is on else clamp bot

                        //there are more options to move to
                        if self.cursor.on_group < self.option_groups.len() as u16 &&
                           self.cursor.on_option + 1 < self.option_groups[self.cursor.on_group as usize].options.len() as u16{
                            self.cursor.on_option += 1;
                        }else if self.cursor.on_group + 1 < self.option_groups.len() as u16{
                            self.cursor.on_group += 1;
                            self.cursor.on_option = 0;
                        }else{
                            self.cursor.on_group = self.option_groups.len() as u16;
                            self.cursor.on_option = 0;
                        }
                    },
                    Key::Up =>{
                        if self.cursor.on_option != 0{
                            self.cursor.on_option -= 1;
                        }else if self.cursor.on_group !=  0{
                            self.cursor.on_option = self.option_groups.len() as u16;
                            self.cursor.on_group  -= 1;
                        }
                    },
                    Key::Char('\n') =>{
                        if self.cursor.on_group == self.option_groups.len() as u16{ // on continue_btn
                            //can only continue if valid
                            if self.validate(){
                                write!(stdout, "{}{}",  termion::scroll::Up(1), termion::cursor::Goto(0,size.1));
                                return Ok(answer_collection);
                            }
                        }else{
                            let group_i     = self.cursor.on_group;
                            let option_i    = self.cursor.on_option;
                            self.toggle_selected_option(group_i, option_i, None)
                        }
                    },
                    Key::Ctrl('c') => {
                        return Err("Terminated process.".to_string());
                    },
                    // Key::Char(c) => {
                    //     print!("{}",c);
                    // },
                    _ => {}
                }

                write!(stdout, "{}",  termion::scroll::Down(line_count));
                let (_answer_collection, _line_count) = self.render_options(size);
                answer_collection = _answer_collection;
                line_count  = _line_count;


            }
            Ok(answer_collection)
        }
    }

    struct ContinueBtn{
        pub valid_appearance   : String,
        pub invalid_appearance : String,
    }

    impl ContinueBtn {
        pub fn get_valid_appearance(&self)->String{
            self.valid_appearance.clone()
        }

        pub fn get_invalid_appearance(&self)->String{
            self.invalid_appearance.clone()
        }

        pub fn set_valid_appearance(&mut self, new_valid_appearance : String)->&mut Self{
            self.valid_appearance = new_valid_appearance;
            self
        }

        pub fn set_invalid_appearance(&mut self, new_invalid_appearance :String)-> &mut Self{
            self.invalid_appearance = new_invalid_appearance;
            self
        }
    }

    impl MultipleChoice{
        pub fn new(message: String) -> MultipleChoice{
            MultipleChoice{
                message            : message,
                prepended_message  : Some("? ".to_owned()),
                option_groups      : vec!(),
                validate_fn        : Box::new(|_| {true}), //always validate to true if not set
                on_select_continue : false,
                cursor             : Cursor{
                    on_group: 0,
                    on_option: 0,
                },
                continue_btn       : ContinueBtn{
                    valid_appearance   : "> Continue >".to_owned(),
                    invalid_appearance : "| Continue |".to_owned()
                }
            }
        }

        pub fn replace_continue_btn(&mut self, valid_appearance : String , invalid_appearance : String)->&mut Self{
            self.continue_btn.valid_appearance = valid_appearance;
            self.continue_btn.invalid_appearance = invalid_appearance;
            self
        }

        pub fn toggle_selected_option(&mut self,  group_index: u16, option_index :u16 , io : Option<bool>){
            if let Some(_io) = io{
                self.option_groups[group_index as usize].options[option_index as usize].selected = _io;
            }else{
                self.option_groups[group_index as usize].options[option_index as usize].selected = !self.option_groups[group_index as usize].options[option_index as usize].selected;
            }
        }

        pub fn render_options(&mut self, size : (u16, u16) )->(AnswerCollection, u16){
            let mut stdout  = stdout().into_raw_mode().unwrap();
            let mut answer_collection = AnswerCollection{answer_sets : vec!()};
            let mut line_count = 0;
            let mut curr_grp = 0;

            for grp in &mut self.option_groups{
                let result = if grp.options.len() < 2{
                    Err("2 or more options must be populated before sending multiple choice.".to_owned())
                }else{
                    //write group name
                    write!(stdout, "{}{}    ==== {} ====", termion::scroll::Up(1), termion::cursor::Goto(0,size.1), grp.name);
                    line_count += 1;

                    let mut curr_option = 0;
                    for option in & grp.options{
                        let selected_icon = if grp.options[curr_option as usize].selected {
                            let large_filled_circle = vec!(0xE2, 0xAC, 0xA4);
                            String::from_utf8_lossy(&large_filled_circle).into_owned()
                        }else{
                            let large_circle = vec!(0xE2, 0x97, 0xAF);
                            String::from_utf8_lossy(&large_circle).into_owned()
                        };

                        let selector_str = if self.cursor.on_group == curr_grp && self.cursor.on_option == curr_option{
                            let selector = vec!(0xE2, 0x98, 0x9B);
                            String::from_utf8_lossy(&selector).into_owned()
                        }else{
                            " ".to_owned()
                        };

                        write!(stdout, "{}{}{}    {}  {}", termion::scroll::Up(1), termion::cursor::Goto(0,size.1), selector_str,  selected_icon, option.name);
                        line_count += 1;
                        curr_option += 1;
                    }



                    Ok("".to_owned())
                };

                //render_selector

                if let Err(_error) = result{ // is an error
                }else{ //is not an error
                    answer_collection.answer_sets.push(grp.to_answerset());
                }
                curr_grp += 1;
            }
            let is_valid = self.validate();
            let continue_str = if is_valid {
                self.continue_btn.get_valid_appearance()
            }else{
                self.continue_btn.get_invalid_appearance()
            };

            let selector_str = if self.cursor.on_group == self.option_groups.len() as u16{
                let selector = vec!(0xE2, 0x98, 0x9B);
                String::from_utf8_lossy(&selector).into_owned()
            }else{
                " ".to_owned()
            };
            write!(stdout, "{}{}{}    {}", termion::scroll::Up(1), termion::cursor::Goto(0,size.1), selector_str, continue_str);
            line_count += 1;
            stdout.flush().unwrap();
            return (answer_collection, line_count);
        }
        //we want the answer collection so that the user can do complex validation.
        pub fn set_validation(&mut self, f : Box<Fn(AnswerCollection)->bool>)->&mut Self{
            self.validate_fn = f;
            self
        }

        fn validate(&mut self)->bool{
            let answer_collection = self.to_answer_collections();
            (self.validate_fn)(answer_collection)
        }

        fn get_option_group_by_name(&mut self, option_group_name : &'static str)->Option<&mut OptionGroup>{
            for opt_grp in &mut self.option_groups{
                if opt_grp.name == option_group_name {
                    return Some(opt_grp)
                }
            }
            None
        }

        pub fn add_option_group(&mut self, option_group : OptionGroup)->&mut Self{
            let mut result = None;
            if let Some(opt_grp) = self.get_option_group_by_name(option_group.name){
                result = Some(format!("A group with the name \"{}\" already exists under the message", opt_grp.name));
            }

            if let Some(mut err_msg) = result {
                err_msg.push_str(&self.message);
                panic!(err_msg);
            }else{
                self.option_groups.push(option_group);
            }
            self
        }

        pub fn to_answer_collections(&mut self)->AnswerCollection{
            let mut answer_collections = AnswerCollection{
                answer_sets : vec!()
            };

            for grp in self.option_groups.iter() {
                answer_collections.answer_sets.push(grp.to_answerset());
            }
            answer_collections
        }
    }

    pub struct AnswerCollection{
        pub answer_sets : Vec<AnswerSet>,
    }

    impl AnswerSet{
        pub fn get_first_answer(&mut self)->Option<String>{

            let result = if self.answers.len() > 0{
                    Some(self.answers[0].clone())
                }else{
                    None
                };

            result
        }
    }

    impl AnswerCollection{
        fn get_answer_set_by_group_name(&mut self,  group_name : &'static str)->Option<& AnswerSet>{
            let mut result = None;
            for answer_set in self.answer_sets.iter() {
                if answer_set.group_name == group_name {
                    result = Some(answer_set);
                    break;
                }
            }
            result
        }

        pub fn get_first_answer(&mut self)->Option<String>{
            if self.answer_sets.len() as u16 > 0{
                self.answer_sets[0].get_first_answer()
            }else{
                None
            }
        }
    }

    pub struct AnswerSet{
        pub group_name : &'static str,
        pub answers    : Vec<String>,
    }

    pub struct Confirm{
        message : String,
        prepended_message : Option<String>
    }

    impl Confirm{
        pub fn new(message : String)->Confirm {
            Confirm{
                message : message,
                prepended_message : Some("? ".to_owned())
            }
        }
    }

    impl TraitQuestion for Confirm{
        fn send(&mut self)->Result<AnswerCollection, String>{
            let mut stdout = stdout().into_raw_mode().unwrap();
            let stdin      = stdin();
            let mut size   = termion::terminal_size().unwrap();
            write!(stdout, "{}{} [Y/n] {}{}", self.prepended_message.as_ref().unwrap_or(&"".to_owned()), self.message, termion::scroll::Up(1), termion::cursor::Goto(0, size.1));

            stdout.flush().unwrap();
            let mut data : Vec<char> = vec!();
            let yes = Regex::new(r"(?i)^y$|^yes$$").unwrap();
            let no = Regex::new(r"(?i)^no$|^n$").unwrap();
            let mut was_unrecognized = false;
            'outer: for c in stdin.keys(){
                // let cursor_position = stdout.cursor_pos().unwrap();
                match c.unwrap(){
                    Key::Char('\n') => {
                        let content = data.iter().cloned().collect::<String>();
                        if yes.is_match(&content) {
                            let answer_collection = AnswerCollection{
                                answer_sets : vec!(AnswerSet{
                                    group_name : "default",
                                    answers    : vec!("yes".to_owned())
                                })
                            };
                           return Ok(answer_collection);
                        }else if no.is_match(&content) {
                            let answer_collection = AnswerCollection{
                                answer_sets : vec!(AnswerSet{
                                    group_name : "default",
                                    answers    : vec!("no".to_owned())
                                })
                            };
                           return Ok(answer_collection);

                        }else{
                            write!(stdout, "{}{}unrecognized response.", termion::clear::CurrentLine, termion::cursor::Goto(0, size.1));
                            was_unrecognized = true;
                            data = vec!();
                            stdout.flush().unwrap();
                        }
                    },
                    Key::Char(c)   => {
                        data.push(c);
                        if was_unrecognized {
                            write!(stdout, "{}{}{}", termion::cursor::Goto(0, size.1), termion::clear::CurrentLine, c);
                            was_unrecognized = false;
                        }else{
                            write!(stdout,"{}",c);
                        }

                    },

                    // Key::Down => {
                    //     write!(stdout, "{}", termion::cursor::Goto(0,size.1));
                    //     println!("");
                    // },
                    // Key::Up => {
                    //     write!(stdout, "{}", termion::cursor::Goto(cursor_position.0, cursor_position.1 - 1));
                    // },
                    Key::Ctrl('c') => break,
                    // Key::Char(c) => println!("{}",c),
                    _ => {}
                }

                stdout.flush().unwrap();
            }

            write!(stdout, "{}{}",termion::cursor::Goto(0, size.1+1), termion::scroll::Up(1)); //new line
            let content = data.iter().cloned().collect::<String>();

            let answer_collection = AnswerCollection{
                answer_sets : vec!(AnswerSet{
                    group_name : "default",
                    answers    : vec!(content.clone())
                })
            };

            Ok(answer_collection)
            // write!(stdout, "{}",termion::cursor::Goto(0, size.1+1)); //new line
        }
    }

    pub struct OpenEnded{
        message      : String,
        prepended_message : Option<String>
    }

    impl OpenEnded{
        pub fn new(message:String) -> OpenEnded{
            OpenEnded{
                message   : message,
                prepended_message : Some("? ".to_owned()),
            }
        }
    }

    impl TraitQuestion for OpenEnded{

        fn send(&mut self)->Result<AnswerCollection, String>{
            let mut stdout = stdout().into_raw_mode().unwrap();
            let stdin      = stdin();
            let mut size   = termion::terminal_size().unwrap();
            write!(
                stdout, "{}{}{}{}",
                self.prepended_message.as_ref().unwrap_or(&"".to_owned()),
                self.message,
                termion::scroll::Up(1),
                termion::cursor::Goto(0,size.1)
            );

            stdout.flush().unwrap();
            let mut data : Vec<char> = vec!();
            for c in stdin.keys(){
                // let cursor_position = stdout.cursor_pos().unwrap();
                match c.unwrap(){
                    Key::Char('\n') => {
                        break;
                    },
                    Key::Char(c)   => {
                        data.push(c);
                        write!(stdout,"{}",c);
                    },
                    // Key::Down => {
                    //     write!(stdout, "{}", termion::cursor::Goto(0,size.1));
                    //     println!("");
                    // },
                    // Key::Up => {
                    //     write!(stdout, "{}", termion::cursor::Goto(cursor_position.0, cursor_position.1 - 1));
                    // },
                    Key::Ctrl('c') => break,
                    // Key::Char(c) => println!("{}",c),
                    _ => {}
                }

                stdout.flush().unwrap();
            }

            write!(stdout, "{}{}",termion::cursor::Goto(0, size.1+1), termion::scroll::Up(1)); //new line
            let content = data.iter().cloned().collect::<String>();

            let answer_collection = AnswerCollection{
                answer_sets : vec!(AnswerSet{
                    group_name : "default",
                    answers    : vec!(content.clone())
                })
            };

            Ok(answer_collection)
            // write!(stdout, "{}",termion::cursor::Goto(0, size.1+1)); //new line
        }
    }

}