termo 0.16.0

yet another terminal ui framework
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
#![allow(unused_imports)]
use std::any::Any;
use std::collections::HashMap;
use std::fmt::Debug;
#[allow(dead_code)]
use std::fmt::Display;
use std::io::Stdout;
use std::ops::RangeTo;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;

use std::time::Duration;
use std::time::Instant;

use colored_json::prelude::*;
use colored_json::to_colored_json_auto;
use colored_json::Color;
use colored_json::ColoredFormatter;
use colored_json::CompactFormatter;
use colored_json::Style;
use colored_json::Styler;
use colored_json::ToColoredJson;
use crossterm::style::StyledContent;
use crossterm::style::Stylize;
use serde_json::Value;

use crate::colors::Printable;
use crate::colors::TimePrintable;
use crate::colors::ALL_COLORS_ANSII;
use crate::PrettyJson;

// SERVING [LINK]
pub fn serving_on(link: &str) {
    "[grey]SERVING[/] ON [green]{link}[/]".print_with(vec![link]);
}
//SERVING [ADDRESS]:[PORT]
pub fn serving(service: &str, link: &str) {
    "[grey]SERVING[/] [green]{service}[/] ON [blue]{link}[/]".print_with(vec![service, link]);
}

// STARTING [SERVICE]
pub fn starting(service: &str, detail: &str) {
    "[yellow]╭─ run ──[/][cyan]─ {service}[/] ── [grey]{detail}[/] ──"
        .print_with(vec![service, detail]);
}

// update [message]
pub fn update(message: &str) {
    "[yellow]│[/] [grey]{message}[/]".print_with(vec![message]);
}

// DONE [SERVICE] IN [DURATION]
pub fn done(service: &str, duration: Duration) {
    "[green]╰─ done ─[/][gray]─ {service}[/] ─[pink]─ {duration} ─[/]─"
        .print_with(vec![service, duration.to_string_s().as_str()]);
}

// STOPPING [SERVICE]
pub fn stopping(service: &str) {
    "[grey]STOPPING[/] [red]{service}[/]".print_with(vec![service]);
}

// RESTARTING [SERVICE]
pub fn restarting(service: &str) {
    "[grey]RESTARTING[/] [yellow]{service}[/]".print_with(vec![service]);
}

// RELOADING [SERVICE]
pub fn reloading(service: &str) {
    "[grey]RELOADING[/] [yellow]{service}[/]".print_with(vec![service]);
}

// OPENING [LINK]
pub fn opening(link: &str) {
    "[grey]OPENING[/] [blue]{link}[/]".print_with(vec![link]);
}

// OPENING [LINK] IN [BROWSER]
pub fn opening_in(link: &str, browser: &str) {
    "[grey]OPENING[/] [blue]{link}[/] IN [green]{browser}[/]".print_with(vec![link, browser]);
}

// OPENING [LINK] IN [BROWSER] IN [DURATION]
pub fn opening_in_duration(link: &str, browser: &str, duration: Duration) {
    "[grey]OPENING[/] [blue]{link}[/] IN [green]{browser}[/] IN [yellow]{duration}[/]"
        .print_with(vec![link, browser, duration.to_string_hms().as_str()]);
}

// STARTED [SERVICE] AT [LINK]
pub fn started(service: &str, link: &str) {
    "[grey]STARTED[/] [green]{service}[/] AT [blue]{link}[/]".print_with(vec![service, link]);
}

// STOPPED [SERVICE] ON [TIME]
pub fn stopped(service: &str, time: &str) {
    "[grey]STOPPED[/] [red]{service}[/] ON [yellow]{}[/]".print_with(vec![service, time]);
}

// RESTARTED [SERVICE] ON [TIME]
pub fn restarted(service: &str, time: &str) {
    "[grey]RESTARTED[/] [yellow]{service}[/] ON [yellow]{}[/]".print_with(vec![service, time]);
}

// RELOADED [SERVICE] ON [TIME]
pub fn reloaded(service: &str, time: &str) {
    "[grey]RELOADED[/] [yellow]{service}[/] ON [yellow]{}[/]".print_with(vec![service, time]);
}

// EXECUTING [COMMAND] [DETAIL]
pub fn executing(command: impl Into<String>, detail: impl Into<String>) {
    "[grey]EXECUTING[/] [green]{}[/] [grey]{}[/]".print_with(vec![command.into(), detail.into()]);
}

pub fn running(path: impl Into<String> + Copy) {
    let path = path.into();
    let length = 40 - path.len();
    let filler = "".repeat(length);
    let path = Path::new(&path);
    let name = path.file_name().unwrap().to_str().unwrap();
    let folder = path.parent().unwrap().to_str().unwrap();
    "\n╭─[on_magenta][black] EXECUTING [/] [purple]{}[/]\n╰─ [dim_gray]from {}[/] {}─╮"
        .print_with(vec![name, folder, &filler]);
}

// EXECUTED [COMMAND] FROM [PATH]
pub fn completed_execution(command: &str, time: impl TimePrintable) {
    "[grey]COMPLETED EXECUTION[/] [green]{}[/] [grey]AT[/] [cyan]{}[/]"
        .print_with(vec![command, time.to_string_hms().as_str()]);
}

// EXECUTED [COMMAND] AS [USER] FROM [PATH]
pub fn executed_as(command: &str, user: &str, path: &str) {
    "[grey]EXECUTED[/] [green]{}[/] AS [green]{user}[/] FROM [blue]{path}[/]"
        .print_with(vec![command, user, path]);
}

// FAILED TO EXECUTE [COMMAND] BECAUSE [REASON]
pub fn failed_to_execute(command: &str, reason: &str) {
    "[grey]FAILED TO EXECUTE[/] [green]{}[/] BECAUSE [red]{reason}[/]"
        .print_with(vec![command, reason]);
}

// FAILED TO EXECUTE [COMMAND] AS [USER] BECAUSE [REASON]
pub fn failed_to_execute_as(command: &str, user: &str, reason: &str) {
    "[grey]FAILED TO EXECUTE[/] [green]{}[/] AS [green]{user}[/] BECAUSE [red]{reason}[/]"
        .print_with(vec![command, user, reason]);
}

// FAILED TO OPEN [LINK] BECAUSE [REASON]
pub fn failed_to_open(link: &str, reason: &str) {
    "[grey]FAILED TO OPEN[/] [blue]{link}[/] BECAUSE [red]{reason}[/]"
        .print_with(vec![link, reason]);
}

// WAITING FOR [SERVICE] TO START
pub fn waiting_for_service_to_start(service: &str) {
    "[grey]WAITING FOR[/] [green]{service}[/] TO START".print_with(vec![service]);
}

// WAITING FOR [SERVICE] TO STOP
pub fn waiting_for_service_to_stop(service: &str) {
    "[grey]WAITING FOR[/] [red]{service}[/] TO STOP".print_with(vec![service]);
}

// WAITING FOR [SOMEONE] TO [SOMETHING]
pub fn waiting_for_someone_to_something(someone: &str, something: &str) {
    "[grey]WAITING FOR[/] [green]{someone}[/] TO [green]{something}[/]"
        .print_with(vec![someone, something]);
}

// COMPLETED [SOMETHING] IN [DURATION] WITH [RESULT]
pub fn completed_in_dur_with_result(
    something: &str,
    duration: Duration,
    result: &str,
) {
    "[grey]COMPLETED[/] [green]{something}[/] IN [yellow]{duration}[/] WITH [green]{result}[/]"
        .print_with(vec![
            something.to_string(),
            duration.to_string_hms(),
            result.to_string(),
        ]);
}

pub fn completed_with_results_in_duration(
    something: impl Into<String>,
    result: impl Into<String>,
    duration: Duration,
) {
    "[grey]COMPLETED[/] [green]{something}[/] WITH [green]{result}[/] IN [yellow]{duration}[/]"
        .print_with(vec![
            something.into(),
            result.into().to_uppercase(),
            duration.to_string_hms(),
        ]);
}

pub fn incoming(kind: impl Into<String>, payload: impl Display) {
    "[yellow]INCOMING[/] [white]{kind}[/] [grey]{payload}[/]"
        .print_with(vec![kind.into(), payload.to_string()]);
}

pub fn incoming_error(kind: impl Into<String>, payload: impl Display) {
    "[yellow]INCOMING[/] [red]{kind}[/] [dark_red]{payload}[/]"
        .print_with(vec![kind.into(), payload.to_string()]);
}

pub fn outgoing(kind: impl Into<String>, payload: impl Display) {
    "[blue]OUTGOING[/] [white]{kind}[/] [grey]{payload}[/]"
        .print_with(vec![kind.into(), payload.to_string()]);
}

pub fn parsed_file(file_path: &str) {
    "[grey]PARSED[/] [blue]{file_path}[/]".print_with(vec![file_path.to_string()]);
}

pub fn found(arg: &str, count: usize) {
    "[grey]FOUND[/] [blue]{arg}[/] [yellow]{count}[/]"
        .print_with(vec![arg.to_string(), count.to_string()]);
}

pub fn error(arg: &str, file_path: &str) {
    "[grey]ERROR[/] [red]{arg}[/] [blue]{file_path}[/]"
        .print_with(vec![arg.to_string(), file_path.to_string()]);
}

pub fn scanning(item: &str, parent: &str) {
    "[grey]SCANNING[/] [cyan]{}[/] [purple]{}[/]"
        .print_with(vec![item.to_string(), parent.to_string()]);
}

pub fn pwd(pwd: &str) {
    "[grey]📂[/] [blue]{}[/]".print_with(vec![pwd.to_string()]);
}

pub fn info(arg: &str) {
    "[grey]INFO[/] [blue]{}[/]".print_with(vec![arg.to_string()]);
}

//FOUND VALID [ARG] [ARG2] [ARG3]
pub fn found_valid(arg: impl Display, arg2: impl Display, arg3: impl Display) {
    "[grey]FOUND VALID[/] [blue]{}[/] [blue]{}[/] [blue]{}[/]".print_with(vec![
        arg.to_string(),
        arg2.to_string(),
        arg3.to_string(),
    ]);
}
// GENERATED CODE FORS [ARG] [ARG2] /n [CODE]
pub fn generated_code(arg: impl Display, arg2: impl Display, code: impl Display) {
    "[grey]GENERATED CODE FOR[/] [blue]{}[/] [blue]{}[/] \n [green]{}[/]".print_with(vec![
        arg.to_string(),
        arg2.to_string(),
        code.to_string(),
    ]);
}

// READING FILE [PATH]
pub fn reading_file(kind: &str, path: &str) {
    "[grey]READ[/] [green]{}[/] [blue]{}[/]".print_with(vec![kind, path]);
}

/// warning
/// [on_yellow]{arg}[/] [yellow]{arg2}[/] \n[gray]{arg3}[/]
pub fn warning(arg: impl Display, arg2: impl Display, arg3: impl Display) {
    "[on_yellow] {arg} [/] [yellow]{arg2}[/] [dim_gray]\n{arg3}[/]".print_with(vec![
        arg.to_string(),
        arg2.to_string(),
        arg3.to_string(),
    ]);
}

/// success
/// [on_green]{arg}[/] [green]{arg2}[/] \n[gray]{arg3}[/]
pub fn success(arg: impl Display, arg2: impl Display, arg3: impl Display) {
    "[on_green] {arg} [/] [green]{arg2}[/] [dim_gray]\n{arg3}[/]".print_with(vec![
        arg.to_string(),
        arg2.to_string(),
        arg3.to_string(),
    ]);
}

pub fn failed_to_read(filename: impl Display, reason: impl Display) {
    "[grey]FAILED TO READ[/] [blue]{}[/] [red]{}[/]"
        .print_with(vec![filename.to_string(), reason.to_string()]);
}

pub fn subtle(line: impl Display) {
    "[grey]{}[/]".print_with(vec![line]);
}

pub fn message(line: impl Display) {
    line.print();
}

pub fn wiped(arg: &str) {
    "[grey]WIPED[/] [blue]{}[/]".print_with(vec![arg.to_string()]);
}

pub fn banner(banner: &str) {
    banner.print();
}

pub fn banner_vibrant(banner: &str) {
    for c in banner.chars() {
        if c == ' ' {
            print!(" ");
        } else {
            let rand = rand::random::<usize>() % ALL_COLORS_ANSII.len();
            let color = ALL_COLORS_ANSII[rand];
            print!("{}{}{}", color, c, "\x1b[0m");
        }
    }
}

/// loaded
/// [gray]LOADED[/] [blue]{arg}[/] [gray]{arg2}[/]
pub fn loaded(arg: impl Display, arg2: impl Display) {
    "[gray]LOADED[/] [blue]{arg}[/] [gray]{arg2}[/]"
        .print_with(vec![arg.to_string(), arg2.to_string()]);
}

pub fn pressed(c: impl Debug) {
    "[grey]PRESSED[/] [blue]{}[/]".print_with(vec![format!("{:?}", c)]);
}

pub fn preparing(arg: impl Into<String>) {
    "[grey]PREPARING[/] [blue]{}[/]".print_with(vec![arg.into()]);
}

// macro
#[macro_export]
//example: msg!("HELLO",some_var,123);
//function: automatically colorizes and prints the message based on the number of arguments
//uses ASCII CODES to colorize the message
//substitutes COLORS_ASCII (array of ascii codes)  before each argument in the message
//output:
// \0x1b[38;5;HELL0\0x1b[38;5;{value_of_some_var}\0x1b[38;5;123\0x1b[0m
// Define the macro
macro_rules! msg {
    ($($arg:expr),*) => {
        {
            // List of ANSI color codes (you can extend this list)
            let color_codes = ["\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34m"];

            // Initialize variables
            let mut msg = String::new();
            let mut is_first = true;
            let mut color_index = 0;

            // Loop through each argument
            $(
                if !is_first {
                    msg.push_str(", ");
                }

                // Append formatted argument with color
                msg.push_str(&format!("{}{}\x1b[0m", color_codes[color_index], $arg));

                // Update variables for next iteration
                is_first = false;
                color_index = (color_index + 1) % color_codes.len();
            )*

            println!("{}", msg);
        }
    };
}

/// sub banner
///  [DO IT ONCE]  DO IT NOMORE  ──────────────────────────────────
pub fn sub_banner(sub: impl Into<String>, tail: impl Into<String>) {
    let sub = sub.into();
    let tail = tail.into();
    let length = 60 - sub.len() - tail.len() - 4;
    let filler = "".repeat(length);
    "[on_yellow][bold] {} [/][yellow] {} [/][gray] {}[/]".print_with(vec![sub, tail, filler]);
}

/// sub banner versioned
/// [SUB][VER] [TAIL]  ──────────────────────────────────────────
pub fn sub_banner_versioned(
    sub: impl Into<String>,
    ver: impl Into<String>,
    tail: impl Into<String>,
) {
    let sub = sub.into();
    let ver = ver.into();
    let tail = tail.into();
    let length = 60 - sub.len() - ver.len() - tail.len() - 4;
    let filler = "".repeat(length);
    "[on_w  hite][black] {} [/][on_cyan] {} [/] {} [/][gray] {}[/]"
        .print_with(vec![sub, ver, tail, filler]);
}

const CONSOLE_WIDTH: usize = 80;

///
/// ╭─ {header} ──────────── __  
/// |       ____ ___  ____  / /_____
/// |      / __ `__ \/ __ \/ __/ __ \
/// |     / / / / / / /_/ / /_/ /_/ /
/// |    /_/ /_/ /_/\____/\__/\____/
/// |
/// ╰─╮─[white] {subtitle} [/]─[yellow] {tail} ─"#;
pub fn banner_framed(
    banner: impl Into<String>,
    header: impl Into<String>,
    tail: impl Into<String>,
) {
    let header = header.into();
    //first print header
    // ╭─ {header} ────────────
    let length = (CONSOLE_WIDTH / 2) - header.len() - 4;
    let filler = "".repeat(length);
    "╭─[yellow][bold] {} [/][gray]{}[/]".print_with(vec![&header, &filler]);
    //next print each line of the banner with "| " prefix
    let banner = banner.into();
    for line in banner.lines() {
        if line.trim().is_empty() {
            continue;
        }
        "│ {}".print_with(vec![&line]);
    }
    //last print tail
    // ╰─╮─[white] {subtitle} [/]─[yellow] {tail} ─"#;
    let tail = tail.into();
    let length = (CONSOLE_WIDTH / 2) - tail.len() - 4;
    let filler = "".repeat(length);
    "╰─╮─[white][bold] {} [/][gray]{}[/]".print_with(vec![&tail, &filler]);
}

// termo::show::headline(vec![ON_WHITE,ON_CYAN,CYAN],vec!["EX","START",exprs.len()]);
// is same as
// let filler = "-".repeat(60- exprs.len().to_string().len()-1 );
//"[on_white][black] EX [/][on_yellow][black] START [/] [cyan]{} [/] {}[/]".print_with(vec![exprs.len().to_string(),filler]);
pub fn headline(colors: Vec<&str>, exprs: Vec<impl Display>) {
    let expressions: Vec<String> = exprs.into_iter().map(|e| e.to_string()).collect();
    let mut length = CONSOLE_WIDTH - expressions.join(" ").len() - 1;

    let mut colored = String::new();
    for (i, expr) in expressions.iter().enumerate() {
        colored.push_str(colors[i]);
        //if i>0 and last char is not " "  then add a space
        if i > 0 && colored.chars().last().unwrap() != ' ' {
            colored.push_str(" ");
            if length > 0 {
                length -= 1;
            }
        }
        colored.push_str(expr);
        colored.push_str(" \x1b[0m");
    }
    //if there is a color at index i then use it for the filler
    if let Some(color) = colors.get(expressions.len()) {
        colored.push_str(color);
    }
    let filler = "".repeat(length);
    colored.push_str(&filler);
    colored.push_str("\x1b[0m");
    println!("{}", colored);
}

/// headline_start - same as headline but starts with "╭─" and ends with "─╮"
/// filler length is adjusted to handle additional 4 chars
pub fn headline_start(colors: Vec<&str>, exprs: Vec<impl Display>) {
    let expressions: Vec<String> = exprs.into_iter().map(|e| e.to_string()).collect();
    let mut length = CONSOLE_WIDTH - expressions.join(" ").len() - 1 - 4;

    let mut colored = String::new();
    for (i, expr) in expressions.iter().enumerate() {
        colored.push_str(colors[i]);
        //if i>0 and last char is not " "  then add a space
        if i > 0 && colored.chars().last().unwrap() != ' ' {
            colored.push_str(" ");
            if length > 0 {
                length -= 1;
            }
        }
        colored.push_str(expr);
        colored.push_str(" \x1b[0m");
    }
    //if there is a color at index i then use it for the filler
    if let Some(color) = colors.get(expressions.len()) {
        colored.push_str(color);
    }
    let filler = "".repeat(length);
    colored.push_str(&filler);
    colored.push_str("\x1b[0m");
    colored.push_str("");
    println!("{}", colored);
}

/// headline_end - same as headline but starts with "╰─" and ends with "─╯"
/// filler length is adjusted to handle additional 4 chars
pub fn headline_end(colors: Vec<&str>, exprs: Vec<impl Display>) {
    let expressions: Vec<String> = exprs.into_iter().map(|e| e.to_string()).collect();
    let mut length = CONSOLE_WIDTH - expressions.join(" ").len() - 1 - 4;

    let mut colored = String::new();
    for (i, expr) in expressions.iter().enumerate() {
        colored.push_str(colors[i]);
        //if i>0 and last char is not " "  then add a space
        if i > 0 && colored.chars().last().unwrap() != ' ' {
            colored.push_str(" ");
            if length > 0 {
                length -= 1;
            }
        }
        colored.push_str(expr);
        colored.push_str(" \x1b[0m");
    }
    //if there is a color at index i then use it for the filler
    if let Some(color) = colors.get(expressions.len()) {
        colored.push_str(color);
    }
    let filler = "".repeat(length);
    colored.push_str(&filler);
    colored.push_str("\x1b[0m");
    colored.push_str("");
    println!("{}", colored);
}

//same as headline but without the filler
pub fn head(colors: Vec<&str>, exprs: Vec<impl Display>) {
    let expressions: Vec<String> = exprs.into_iter().map(|e| e.to_string()).collect();
    let mut colored = String::new();
    for (i, expr) in expressions.iter().enumerate() {
        colored.push_str(colors[i]);
        //if i>0 and last char is not " "  then add a space
        if i > 0 && colored.chars().last().unwrap() != ' ' {
            colored.push_str(" ");
        }
        colored.push_str(expr);
        colored.push_str(" \x1b[0m");
    }
    println!("{}", colored);
}

/// positioned
/// args
/// x:usize - offset from left of current line
/// y:usize - offset from top of current line
/// text:&str - text to be printed
pub fn positioned(x: i16, y: i16, text: impl Into<String>) {
    let current = crossterm::cursor::position().unwrap();

    // find the difference between current position and the new position
    // x and y provided are relative to current position. so if x= -1 and y = -1 then the new position is one row up and one column left
    let nx = match x {
        x if x < 0 => current.0 - (x.abs() as u16),
        x if x > 0 => current.0 + (x.abs() as u16),
        _ => current.0,
    };
    let ny = match y {
        y if y < 0 => current.1 - (y.abs() as u16),
        y if y > 0 => current.1 + (y.abs() as u16),
        _ => current.1,
    };

    crossterm::execute!(std::io::stdout(), crossterm::cursor::MoveTo(nx, ny)).unwrap();
    text.into().print();
    crossterm::execute!(
        std::io::stdout(),
        crossterm::cursor::MoveTo(current.0, current.1)
    )
    .unwrap();
}

/// divider
/// ──────────────── (WIDTH)
pub fn divider() {
    "".repeat(CONSOLE_WIDTH).print();
}

pub fn positioned_divider(x: i16, y: i16) {
    let current = crossterm::cursor::position().unwrap();

    // find the difference between current position and the new position
    // x and y provided are relative to current position. so if x= -1 and y = -1 then the new position is one row up and one column left
    let nx = match x {
        x if x < 0 => current.0 - (x.abs() as u16),
        x if x > 0 => current.0 + (x.abs() as u16),
        _ => current.0,
    };
    let ny = match y {
        y if y < 0 => current.1 - (y.abs() as u16),
        y if y > 0 => current.1 + (y.abs() as u16),
        _ => current.1,
    };
    crossterm::execute!(std::io::stdout(), crossterm::cursor::MoveTo(nx, ny)).unwrap();
    divider();
    crossterm::execute!(
        std::io::stdout(),
        crossterm::cursor::MoveTo(current.0, current.1)
    )
    .unwrap();
}

/// div_text_center
/// ──────────────── (WIDTH/2)-1 [TEXT] ──────────────── (WIDTH/2)-1
pub fn div_text_center(text: impl Into<String>) {
    let text = text.into();
    let length = (CONSOLE_WIDTH / 2) - text.len() - 1;
    let filler = "".repeat(length);
    format!("{} {} {}", filler, text, filler).print();
}

/// div_text_left
/// [TEXT] ──────────────── (WIDTH-TEXT.len())
pub fn div_text_left(text: impl Into<String>) {
    let text = text.into();
    let length = CONSOLE_WIDTH - text.len() - 1;
    let filler = "".repeat(length);
    format!("{} {}", text, filler).print();
}

/// div_text_right
/// ──────────────── (WIDTH-TEXT.len()) [TEXT]
pub fn div_text_right(text: impl Into<String>) {
    let text = text.into();
    let length = CONSOLE_WIDTH - text.len() - 1;
    let filler = "".repeat(length);
    format!("{} {}", filler, text).print();
}

/// div_vibrant
/// ──────── each char is colored with a random color
pub fn div_vibrant() {
    for _ in 0..CONSOLE_WIDTH {
        let rand = rand::random::<usize>() % ALL_COLORS_ANSII.len();
        let color = ALL_COLORS_ANSII[rand];
        print!("{}{}", color, "\x1b[0m");
    }
}

pub fn divider_positioned_vibrant(x: i16, y: i16) {
    let current = crossterm::cursor::position().unwrap();

    // find the difference between current position and the new position
    // x and y provided are relative to current position. so if x= -1 and y = -1 then the new position is one row up and one column left
    let nx = match x {
        x if x < 0 => current.0 - (x.abs() as u16),
        x if x > 0 => current.0 + (x.abs() as u16),
        _ => current.0,
    };
    let ny = match y {
        y if y < 0 => current.1 - (y.abs() as u16),
        y if y > 0 => current.1 + (y.abs() as u16),
        _ => current.1,
    };
    crossterm::execute!(std::io::stdout(), crossterm::cursor::MoveTo(nx, ny)).unwrap();
    div_vibrant();
    crossterm::execute!(
        std::io::stdout(),
        crossterm::cursor::MoveTo(current.0, current.1)
    )
    .unwrap();
}

pub fn substitute(v: impl Into<String>, u: impl Into<String>) {
    let v = v.into();
    let u = u.into();
    "[gray]SUBSTITUTING[/] [blue]{}[/] [gray]WITH[/] [blue]{}[/]".print_with(vec![v, u]);
}

pub fn not_found(arg: &str, v: &str) {
    "[red]─ ! ── [/][dim_gray]{}[/] [red]NOT FOUND ─── [/][yellow]{}[/]".print_with(vec![arg, v]);
}

pub fn sub_value(to_string: &str, value: serde_json::Value) {
    "|         ╰─► [yellow]SET[/][dim_gray] VALUE ─╮─► [/][magenta]{}[/]".print_with(vec![to_string]);
    let msg = (&value.to_string())
        .to_colored_json_with_styler(
            ColorMode::default().eval(),
            Styler {
                key: Style::new(Color::Green).bold(),
                string_value: Style::new(Color::Blue).italic(),
                integer_value: Style::new(Color::Magenta).bold(),
                float_value: Style::new(Color::Magenta).bold(),
                object_brackets: Style::new(Color::Yellow),
                array_brackets: Style::new(Color::Cyan),
                ..Default::default()
            },
        )
        .unwrap_or_else(|_| "ERROR".to_string());
    //for each line add a prefix "|         "
    let mut lines: Vec<String> = msg.lines().map(|l| format!("│    │ {}", l)).collect();
    //add start line "      ╭─────"
    lines.insert(0, "│    ╭───────────────────╯".to_string());
    //add end line "      ╰─────"
    lines.push("│    ╰───────────────────────".to_string());
    "{}".print_with(vec![lines.join("\n")]);
}

pub fn sub_key(to_string: &str) {
    "│           ╰─► [pink]{}[/] ─".print_with(vec![to_string]);
}


/// #json
/// display anyhting in a beautiful way
/// ╭───── {a} ── {b} ──
/// |  property: value
/// |  property: value
/// |  property: value
/// |  last_property: value
/// ╰─────────────────────────────────
/// should be able to display anything that implemets Debug trait
/// wrapped in a box and chopps max 60 chars(including the box) into next line
/// and prefixes each line with "│  " 
pub fn thing(a: impl Into<String>, b: impl Into<String>, c: impl Display) {
    let a = a.into();
    let b = b.into();
    let length = 60 - a.len() - b.len() - 4;
    let filler = "".repeat(length);
    "╭───── [dim_gray]{}[/] [blue]{}[/] {}─"
        .print_with(vec![a, b, filler]);
    let msg = (&c.to_string())
        .to_colored_json_with_styler(
            ColorMode::default().eval(),
            Styler {
                key: Style::new(Color::Green).bold(),
                string_value: Style::new(Color::Blue).italic(),
                integer_value: Style::new(Color::Magenta).bold(),
                float_value: Style::new(Color::Magenta).bold(),
                object_brackets: Style::new(Color::Yellow),
                array_brackets: Style::new(Color::Cyan),
                ..Default::default()
            },
        )
        .unwrap_or_else(|_| "ERROR".to_string());
    //for each line add a prefix "|         "
    let mut lines: Vec<String> = msg.lines().map(|l| format!("{}", l)).collect();
  // add tail line "╰─────────────────────────────────"
    lines.push("╰─────────────────────────────────".to_string());
    "{}".print_with(vec![lines.join("\n")]);

}

/// termo::show::anything!("name",thing);
/// display anyhting in a beautiful way
/// ╭───── {name} ────────────────────
/// |  property: value
/// |  property: value
/// |  property: value
/// |  last_property: value
/// ╰─────────────────────────────────
/// should be able to display anything that implemets Debug trait
/// wrapped in a box and chopps max 60 chars(including the box) into next line
/// and prefixes each line with "│  " 
#[macro_export]
macro_rules! anything {
    //handle name + type + object
    ($name:expr,$type:expr,$object:expr) => {
        {
            use termo::show::*;
            use termo::colors::*;

            let name = $name;
            let type_ = $type;
            let object = $object;
            termo::show::thing(name, type_,object);
        }
    };
    //handle name and object
    ($name:expr,$object:expr) => {
        {
            use termo::show::*;
            use termo::colors::*;

            let name = $name;
            let object = $object;
            termo::show::thing(name, "",object);
        }
    };

    //handle just object
    ($object:expr) => {
        {
            use termo::show::*;
            use termo::colors::*;

            let object = $object;
            termo::show::thing("value","",object);

        }
    };




}

pub fn json(json: impl Into<Value>) {
    let json = json.into();
    let msg = (&json.to_string())
        .to_colored_json_with_styler(
            ColorMode::default().eval(),
            Styler {
                key: Style::new(Color::Green).bold(),
                string_value: Style::new(Color::Blue).italic(),
                integer_value: Style::new(Color::Magenta).bold(),
                float_value: Style::new(Color::Magenta).bold(),
                object_brackets: Style::new(Color::Yellow),
                array_brackets: Style::new(Color::Cyan),
                ..Default::default()
            },
        )
        .unwrap_or_else(|_| "ERROR".to_string());
    //for each line add a prefix "|         "
    let mut lines: Vec<String> = msg.lines().map(|l| format!("{}", l)).collect();
    //add start line "      ╭─────"
    lines.insert(0, "╭─────".to_string());
    //add end line "      ╰─────"
    lines.push("╰─────".to_string());
    "{}".print_with(vec![lines.join("\n")]);
}



pub fn chop(text: impl Into<String>, max: usize) -> String {
    let text = text.into();
    if text.len() > max {
        return format!("{}...", &text[0..max - 3]);
    }
    text
}

/// ╭── READING {TYPE} {FILE} ─
pub fn reading(type_: impl Into<String>, file: impl Into<String>) {
    let type_ = type_.into();
    let file = file.into();
    let length = 60 - type_.len() - file.len() - 4;
    let filler = "".repeat(length);
    "╭── [dim_gray]READING[/] [blue]{}[/] [yellow]{}[/] {}─"
        .print_with(vec![type_, file, filler]);
}
/// ╭── STARTED EXECUTING [COMMAND] ON [TIME] ─ 
pub fn starting_execution(scope: impl Into<String>, command: impl Into<String>) {
    let start = "RUNNING".to_string();
    let scope = scope.into();
    let command = command.into().to_uppercase();
    let length = 60 - scope.len() - command.len() - start.len() - 4;
    let filler = "".repeat(length);
    "\n╭── [dim_gray]{}[/] [cyan]{}[/] [green]{}[/] {}─"
        .print_with(vec![start, scope, command, filler]);
}

// COMPLETED [SOMETHING] IN [DURATION]
pub fn completed_in_dur(something: impl Into<String>, duration: Duration) {
    let start = "COMPLETED".to_string();
    let something = something.into().to_uppercase();
    let duration = duration.to_string_ms();
    let length = 60 - something.len() - duration.len() - start.len() - 4;
    let filler = "".repeat(length);
    "╰── [dim_gray]{}[/] [green]{}[/] [yellow]{}[/] {}─\n"
        .print_with(vec![start, something, duration, filler]);
}

// [ACTION] [COMMAND] [DETAIL]
pub fn action(action: impl Into<String>, command: impl Into<String>, detail: impl Into<String>) {
    let detail = chop(detail, 40);
    let command = chop(command, 40);
    let action = chop(action, 10);
    "| [dim_gray]{} ─·─► [/][cyan]{}[/] [white]{}[/]".print_with(vec![action, command, detail]);
}

// [SUBACTION] [COMMAND] [DETAIL]
pub fn sub_action(
    subaction: impl Into<String>,
    command: impl Into<String>,
    detail: impl Into<String>,
) {
    let detail = chop(detail, 40);
    let command = chop(command, 40);
    let subaction = chop(subaction, 10);

    if detail.clone().is_empty() {
        "| [dim_gray]      ╰─► [/][yellow]{}[/] [white]{}[/]".print_with(vec![subaction, command]);
        return;
    } else {
        "| [dim_gray]      ╰─► [/][yellow]{}[/][dim_gray] ─► [white]{}[/] [gray]{}[/]"
            .print_with(vec![subaction, command, detail]);
    }
}

/// termo::show::key(soemthing)
/// ╰─ [pink]something[/]
pub fn key(key: impl Into<String>, order: usize) {
    let key = key.into();
    let intend = " ".repeat(order * 2);
    "|          {}╰─ [pink]{}[/]".print_with(vec![intend, key]);
}

/// ──── [green]{action}[dim_gray] ─·─ [/][cyan]{command}[/] [white]{detail}[/] ────
pub fn action_complete(
    action: impl Into<String>,
    command: impl Into<String>,
    detail: impl Into<String>,
) {
    let detail = chop(detail, 40);
    let command = chop(command, 40);
    let action = chop(action, 10);
    let length = 40 - action.len() - command.len() - detail.len() - 4;
    let filler = "".repeat(length);
    "╰─[green]╮[/]".print();
    "  [green]╰─► {} [/][yellow]{}[/][dim_gray] ──► [/]{}[dim_gray] {}[/]"
        .print_with(vec![action, command, detail, filler]);
    "╭─[green]╯[/]".print();
}

/// ╰─ [pink]{key}[/] [white]{length}[/]
pub fn sub_array(r#in: &str, len: usize, intend: usize) {
    let intend = "   ".to_string();
    "|{}╰─► [pink]{}[/] ([white]{}[/] [dim_gray]NOS[/])".print_with(vec![
        intend,
        r#in.to_string(),
        len.to_string(),
    ]);
}

pub fn action_loop(arg: impl Into<String>, detail: impl Into<String>) {
    let arg = arg.into();
    let detail = detail.into();
    "|[dim_gray] LOOP ─·─╮[/]".print();
    "|[dim_gray]   | [/][yellow]{}[/] | [dim_gray]{}[/] ".print_with(vec![arg, detail]);
}