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
// File: style.rs

use std::fmt::{Display, Formatter, Result};

pub mod banner;

/// Struct to represent a console style
pub struct CStyle(pub &'static str);

impl Display for CStyle {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "{}", self.0)
    }
}

pub const RESET_COLOR: &str = "\x1b[0m";

/// Trait to provide styling and printing functionalities
pub trait Stylable {

    fn print(&self);
    fn println(&self);
    fn show(&self, style: &CStyle) {
        print!("{}", self.wrap_reset(style));
    }
    fn showln(&self, style: &CStyle) {
        println!("{}", self.wrap_reset(style));
    }

    fn style(&self, style: &CStyle) -> String {
        self.wrap_reset(style)
    }



    fn wrap_reset(&self, style: &CStyle) -> String;
    fn in_bold(&self) -> String;
    fn in_dim(&self) -> String;
    fn in_italic(&self) -> String;
    fn in_underline(&self) -> String;
    fn in_blink(&self) -> String;
    fn in_gray(&self) -> String;
    fn in_red(&self) -> String;
    fn in_green(&self) -> String;
    fn in_yellow(&self) -> String;
    fn in_blue(&self) -> String;
    fn in_magenta(&self) -> String;
    fn in_cyan(&self) -> String;
    fn in_white(&self) -> String;
    fn in_orange(&self) -> String;
    fn in_pink(&self) -> String;
    fn in_purple(&self) -> String;
    fn on_gray(&self) -> String;
    fn on_red(&self) -> String;
    fn on_green(&self) -> String;
    fn on_yellow(&self) -> String;
    fn on_blue(&self) -> String;
    fn on_magenta(&self) -> String;
    fn on_cyan(&self) -> String;
    fn on_white(&self) -> String;
    fn on_orange(&self) -> String;
    fn on_pink(&self) -> String;
    fn on_purple(&self) -> String;
    fn subtle(&self) -> String;
    fn as_info(&self) -> String;
    fn as_success(&self) -> String;
    fn as_warning(&self) -> String;
    fn as_error(&self) -> String;
    fn as_debug(&self) -> String;
    fn with_nostyle(&self) -> String;
    fn vibrant(&self) -> String;


    /// Print the text at a specific position
    /// `x` and `y` are offsets from the current position
    fn print_positioned<F>(&self, x: i32, y: i32, func: F)
    where
        F: Fn(&str) -> String;
}

impl<T: Display> Stylable for T {


    fn print(&self) {
        print!("{}", self);
    }

    fn println(&self) {
        println!("{}", self);
    }


    fn wrap_reset(&self, style: &CStyle) -> String {
        format!("{}{}{}", style, self, RESET_COLOR)
    }

    fn in_bold(&self) -> String { self.wrap_reset(&CStyle("\x1b[1m")) }
    fn in_dim(&self) -> String { self.wrap_reset(&CStyle("\x1b[2m")) }
    fn in_italic(&self) -> String { self.wrap_reset(&CStyle("\x1b[3m")) }
    fn in_underline(&self) -> String { self.wrap_reset(&CStyle("\x1b[4m")) }
    fn in_blink(&self) -> String { self.wrap_reset(&CStyle("\x1b[5m")) }
    fn in_gray(&self) -> String { self.wrap_reset(&CStyle("\x1b[90m")) }
    fn in_red(&self) -> String { self.wrap_reset(&CStyle("\x1b[91m")) }
    fn in_green(&self) -> String { self.wrap_reset(&CStyle("\x1b[92m")) }
    fn in_yellow(&self) -> String { self.wrap_reset(&CStyle("\x1b[93m")) }
    fn in_blue(&self) -> String { self.wrap_reset(&CStyle("\x1b[94m")) }
    fn in_magenta(&self) -> String { self.wrap_reset(&CStyle("\x1b[95m")) }
    fn in_cyan(&self) -> String { self.wrap_reset(&CStyle("\x1b[96m")) }
    fn in_white(&self) -> String { self.wrap_reset(&CStyle("\x1b[97m")) }
    fn in_orange(&self) -> String { self.wrap_reset(&CStyle("\x1b[38;5;208m")) }
    fn in_pink(&self) -> String { self.wrap_reset(&CStyle("\x1b[38;5;205m")) }
    fn in_purple(&self) -> String { self.wrap_reset(&CStyle("\x1b[38;5;129m")) }
    fn on_gray(&self) -> String { self.wrap_reset(&CStyle("\x1b[100m")) }
    fn on_red(&self) -> String { self.wrap_reset(&CStyle("\x1b[101m")) }
    fn on_green(&self) -> String { self.wrap_reset(&CStyle("\x1b[102m")) }
    fn on_yellow(&self) -> String { self.wrap_reset(&CStyle("\x1b[103m")) }
    fn on_blue(&self) -> String { self.wrap_reset(&CStyle("\x1b[104m")) }
    fn on_magenta(&self) -> String { self.wrap_reset(&CStyle("\x1b[105m")) }
    fn on_cyan(&self) -> String { self.wrap_reset(&CStyle("\x1b[106m")) }
    fn on_white(&self) -> String { self.wrap_reset(&CStyle("\x1b[107m")) }
    fn on_orange(&self) -> String { self.wrap_reset(&CStyle("\x1b[48;5;208m")) }
    fn on_pink(&self) -> String { self.wrap_reset(&CStyle("\x1b[48;5;205m")) }
    fn on_purple(&self) -> String { self.wrap_reset(&CStyle("\x1b[48;5;129m")) }
    fn subtle(&self) -> String { self.wrap_reset(&CStyle("\x1b[90m")) }
    fn as_info(&self) -> String { self.wrap_reset(&CStyle("\x1b[96m")) }
    fn as_success(&self) -> String { self.wrap_reset(&CStyle("\x1b[92m")) }
    fn as_warning(&self) -> String { self.wrap_reset(&CStyle("\x1b[93m")) }
    fn as_error(&self) -> String { self.wrap_reset(&CStyle("\x1b[91m")) }
    fn as_debug(&self) -> String { self.wrap_reset(&CStyle("\x1b[95m")) }
    fn with_nostyle(&self) -> String { format!("{}", self) }

    fn vibrant(&self) -> String {
        let mut result = String::new();
        for c in self.to_string().chars() {
            if c == ' ' {
                result.push(c);
            } else {
                let color = rand::random::<u8>() % 216 + 16; // colors from 16 to 231 are more saturated
                result.push_str(&format!("\x1b[38;5;{}m{}\x1b[0m", color, c));
            }
        }
        result
    }

    fn print_positioned<F>(&self, x: i32, y: i32, func: F)
    where
        F: Fn(&str) -> String,
    {
        if x < 0 {
            print!("\x1b[{}A", x.abs());
        }
        if x > 0 {
            print!("\x1b[{}B", x);
        }
        if y < 0 {
            print!("\x1b[{}D", y.abs());
        }
        if y > 0 {
            print!("\x1b[{}C", y);
        }
        print!("{}", func(&self.to_string()));
        if x < 0 {
            print!("\x1b[{}B", x.abs());
        }
        if x > 0 {
            print!("\x1b[{}A", x);
        }
        if y < 0 {
            print!("\x1b[{}C", y.abs());
        }
        if y > 0 {
            print!("\x1b[{}D", y);
        }
        io::stdout().flush().unwrap();
    }
}

// File: utils.rs

pub use super::*;
pub use ask::*;

use std::io::{self, Write};
use std::sync::RwLock;

/// Print the provided text at the provided position, offset by the provided x and y values from the current position
/// `x` and `y` can be negative to move the cursor to the left or up
/// e.g. `print_positioned(0,0,"hello world")` prints "hello world" at the current position
pub fn print_positioned(x: i16, y: i16, text: impl Into<String>) {
    let text = text.into();
    let (xor, yor) = cursor::position().unwrap();
    let adjusted_x = x + xor as i16;
    let adjusted_y = y + yor as i16;
    print!("\x1b[{};{}H{}", adjusted_x, adjusted_y, text);
    print!("\x1b[{};{}H", xor, yor);
}

/// Reset the cursor to the beginning of the line
pub fn reset_line() {
    print!("\x1b[0G");
}

/// Move the cursor up by `n` lines
pub fn move_up(n: i16) {
    print!("\x1b[{}A", n);
}

/// Move the cursor down by `n` lines
pub fn move_down(n: i16) {
    print!("\x1b[{}B", n);
}

/// Move the cursor right by `n` columns
pub fn move_right(n: i16) {
    print!("\x1b[{}C", n);
}

/// Move the cursor left by `n` columns
pub fn move_left(n: i16) {
    print!("\x1b[{}D", n);
}

/// Clear the current line
pub fn clear_line() {
    print!("\x1b[2K");
}

/// Clear the entire screen
pub fn clear_screen() {
    print!("\x1b[2J");
}

/// Enable raw mode on stdin (no external dependencies)
pub fn enable_raw_mode() -> std::io::Result<()> {
    io::stdout().write_all(b"\x1b[?25l")?;
    io::stdout().flush()?;
    Ok(())
}

/// Disable raw mode on stdin (no external dependencies)
pub fn disable_raw_mode() -> std::io::Result<()> {
    io::stdout().write_all(b"\x1b[?25h")?;
    io::stdout().flush()?;
    Ok(())
}

/// Lazy static to store modifiable configuration for max width
lazy_static::lazy_static! {
    static ref MAX_WIDTH: RwLock<usize> = RwLock::new(60);
}

/// Get the maximum width for wrapping text
pub fn get_max_width() -> usize {
    *MAX_WIDTH.read().unwrap()
}

/// Set the maximum width for wrapping text
pub fn set_max_width(width: usize) {
    *MAX_WIDTH.write().unwrap() = width;
}

/// Wrap text to fit the specified width
pub fn wrap_text(text: impl Into<String>, width: usize) -> String {
    let mut wrapped = textwrap::fill(&text.into(), width);
    wrapped = wrapped.trim_end().to_string();
    wrapped
}

/// Print a divider as per max width
pub fn divider() {
    print!("\x1b[0G");
    println!("\x1b[90m{}\x1b[0m", "─".repeat(get_max_width()));
}

/// Macro to print a divider with optional text and styles
#[macro_export]
macro_rules! divider {
    () => {
        $crate::divider();
    };
    ($($arg:tt)*) => {
        {
            use std::io::{self, Write};
            let stdout = io::stdout();
            let mut stdout = stdout.lock();
            let width = $crate::get_max_width();
            let mut left = String::new();
            let mut center = String::new();
            let mut right = String::new();
            let mut chars = "─".to_string();
            let mut args = vec![$($arg)*];
            let mut has_left = false;
            let mut has_right = false;
            while let Some(arg) = args.pop() {
                match arg {
                    "-" => {
                        if center.is_empty() {
                            has_left = true;
                        } else {
                            has_right = true;
                        }
                    }
                    "/" => {
                        if left.is_empty() {
                            left.push('╭');
                        } else {
                            right.push('╮');
                        }
                    }
                    "\\" => {
                        if left.is_empty() {
                            left.push('╰');
                        } else {
                            right.push('╯');
                        }
                    }
                    "=" => {
                        chars = "═".to_string();
                    }
                    s => {
                        if center.is_empty() {
                            center = s.to_string();
                        } else {
                            center = format!("{} {}", center, s.to_string());
                        }
                    }
                }
            }
            let content_width = center.len();
            let mut left_width = 0;
            let mut right_width = 0;
            if has_left && has_right {
                let remaining_width = width - content_width - 2;
                if remaining_width >= 2 {
                    left_width = remaining_width / 2;
                    right_width = remaining_width - left_width;
                }
            } else if has_left {
                left_width = width - content_width - 1;
            } else if has_right {
                right_width = width - content_width - 1;
            } else {
                let remaining_width = width - content_width;
                if remaining_width >= 2 {
                    left_width = remaining_width / 2;
                    right_width = remaining_width - left_width;
                }
            }
            left = chars.repeat(left_width) + &left;
            right = right + &chars.repeat(right_width);
            let output = if has_left && has_right {
                format!("{} {} {}", left, center, right)
            } else if has_left {
                format!("{} {}", left, center)
            } else if has_right {
                format!("{} {}", center, right)
            } else {
                format!("{}{}{}", left, center, right)
            };
            write!(stdout, "\x1b[0G\x1b[90m{:\u{2500}<width$}\x1b[0m\n", output, width = width).unwrap();
        }
    };
}

/// Print a divider with vibrant colors
pub fn divider_vibrant() {
    print!("\x1b[0G");
    let mut s = String::new();
    for _ in 0..get_max_width() {
        let color = rand::random::<u8>() % 216 + 16; // colors from 16 to 231 are more saturated
        s.push_str(format!("\x1b[38;5;{}m{}\x1b[0m", color, "—").as_str());
    }
    println!("{}", s);
}

/// Print the provided text in a frame of x, y, w, h
/// Automatically wraps the text to fit the width of the frame
pub fn print_framed(x: i16, y: i16, w: i16, h: i16, text: impl Into<String>) {
    let (xor, yor) = cursor::position().unwrap();
    let text = text.into();
    let width = w as usize;
    let height = h as usize;
    let wrapped = wrap_text(text, width);
    let mut lines = wrapped.lines();
    for i in 0..height {
        if let Some(line) = lines.next() {
            print!("\x1b[{};{}H{}", x + i as i16, y, line);
        }
    }
    print!("\x1b[{};{}H", xor, yor);
}

use lazy_static::lazy_static;
use std::sync::{Arc, Mutex};

/// Add a space before and after the text (if not already present)
fn pad_text(text: impl Into<String>) -> String {
    let text = text.into();
    if text.starts_with(' ') {
        format!(" {}", text)
    } else {
        format!(" {}", text)
    }
}

/// Pickable trait to be implemented for pickable items
pub trait Pickable {
    fn get_title(&self) -> String;
    fn get_description(&self) -> String;
}

#[macro_export]
macro_rules! show {
    ($arg:expr) => {
        print!("{}", $arg);
    };

    ($style:ident, $value:expr) => {
        print!("{}{}{}", $crate::$style, $value, $crate::RESET_COLOR);
    };

    ($style:ident, $value:expr, $($rest:tt)*) => {
        $crate::show!($style, $value);
        $crate::show!($($rest)*);
    };
}

#[macro_export]
macro_rules! showln {
    ($arg:expr) => {
        println!("{}", $arg);
    };

    ($style:ident, $value:expr) => {
        println!("{}{}{}", $crate::$style, $value, $crate::RESET_COLOR);
    };

    ($style:ident, $value:expr, $($rest:tt)*) => {
        $crate::show!($style, $value);
        $crate::showln!($($rest)*);
    };
}

/// Same as `show!` but returns a string instead of printing it
#[macro_export]
macro_rules! render {
    ($arg:expr) => {
        $arg.to_string()
    };

    ($style:ident, $value:expr) => {
        format!("{}{}{}", $crate::$style, $value, $crate::RESET_COLOR)
    };

    ($style:ident, $value:expr, $($rest:tt)*) => {
        format!("{}{}{}", $crate::$style, $value, $crate::RESET_COLOR) + &$crate::render!($($rest)*)
    };
}





pub use textwrap::*;
/// Macro to print a paragraph with a title and text
/// The text is automatically wrapped to the max width
#[macro_export]
macro_rules! paragraph {
    ($title_style:ident, $title:expr, $text_style:ident, $text:expr) => {
        let title = $title.to_string();
        showln!($title_style, "╭─ ", $title_style, title, $title_style, " ─");
        let text = $text.to_string();
        let width = $crate::get_max_width() - 3;
        let mut wrapped = $crate::wrap_text(&text, width);
        wrapped = wrapped.trim_end().to_string();
        for line in wrapped.lines() {
            showln!($title_style, "│ ", $text_style, line);
        }
        showln!($title_style, "╰─",$title_style, "─".repeat(width));
    };
}

/// Macro to print a tree of the provided serializable object
#[macro_export]
macro_rules! tree {
    ($val:expr) => {
        fn display_tree(value: &Value, indent: usize) {
            match value {
                Value::Object(map) => {
                    println!(
                        "{}╭─ {}object{}",
                        "│ ".repeat(indent),
                        $crate::purple_bold,
                        $crate::RESET_COLOR
                    );
                    for (key, value) in map {
                        println!("{}{} ", "│ ".repeat(indent + 1), key);
                        display_tree(value, indent + 1);
                    }
                    println!("{}╰─—", "│ ".repeat(indent));
                }
                Value::Array(array) => {
                    println!(
                        "{}╭─ {}array{}",
                        "│ ".repeat(indent),
                        $crate::purple_bold,
                        $crate::RESET_COLOR
                    );
                    for (index, value) in array.iter().enumerate() {
                        println!("{}{}: ", "│ ".repeat(indent + 1), index);
                        display_tree(value, indent + 1);
                    }
                    println!("{}╰─—", "│ ".repeat(indent));
                }
                Value::String(string) => {
                    println!(
                        "{}{}{}{}",
                        "│ ".repeat(indent),
                        $crate::green,
                        string,
                        $crate::RESET_COLOR
                    );
                }
                Value::Number(number) => {
                    println!(
                        "{}{}{}{}",
                        "│ ".repeat(indent),
                        $crate::yellow,
                        number,
                        $crate::RESET_COLOR
                    );
                }
                Value::Bool(boolean) => {
                    println!(
                        "{}{}{}{}",
                        "│ ".repeat(indent),
                        $crate::blue,
                        boolean,
                        $crate::RESET_COLOR
                    );
                }
                Value::Null => {
                    println!(
                        "{}{}{}{}",
                        "│ ".repeat(indent),
                        $crate::gray,
                        "null",
                        $crate::RESET_COLOR
                    );
                }
            }
        }
        display_tree(&$val, 0);
    };
}

pub use ask::*;
pub mod ask;

pub fn code_to_char(code: &KeyCode) -> char {
    match code {
        KeyCode::Char(c) => *c,
        KeyCode::Enter => '\n',
        KeyCode::Backspace => '\x08',
        KeyCode::Esc => '\x1b',
        KeyCode::Tab => '\t',
        KeyCode::Up => '↑',
        KeyCode::Down => '↓',
        KeyCode::Left => '←',
        KeyCode::Right => '→',
        _ => ' ',
    }
}