odd-box 0.1.10

a dead simple reverse proxy server and web server
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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
use crossterm::event::{KeyEvent, KeyModifiers};
use ratatui::layout::{Alignment, Margin};
use ratatui::style::{Color, Modifier, Style, Stylize };
use ratatui::text::Line;
use ratatui::widgets::{BorderType, List, ListItem };
use tokio::task;
use tracing::level_filters::LevelFilter;
use tracing::Level;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::layer::SubscriberExt;
use std::io::Stdout;
use std::str::FromStr;
use crate::global_state::GlobalState;
use crate::logging::SharedLogBuffer;
use crate::logging::LogMsg;
use crate::types::app_state::*;
use crate::types::odd_box_event::Event as OddBoxEvent;
use crate::types::tui_state::{Page, TuiSiteWindowState, TuiState};
use std::sync::{Arc, Mutex};
use crate::http_proxy::ProcMessage;

use serde::ser::SerializeStruct;

mod connections_widget;
mod logs_widget;
mod stats_widget;
mod threads_widget;
pub mod scroll_state_wrapper;

use ratatui::{
    layout::{Constraint, Direction, Layout},
    widgets::{Block, Borders, Paragraph}
};

use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
    execute,
    terminal::{
        disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};

use ratatui::{
    backend::CrosstermBackend,
    Terminal,
};

impl serde::Serialize for LogMsg {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer {
        let mut s = serializer.serialize_struct("LogMsg", 4)?;
        s.serialize_field("msg", &self.msg)?;
        s.serialize_field("lvl", &self.lvl.as_str())?;
        s.serialize_field("src", &self.src)?;
        s.serialize_field("thread", &self.thread.as_ref().unwrap_or(&"".to_string()))?;
        s.end()

    }
}


pub fn init() {
    _ = enable_raw_mode().expect("must be able to enable raw mode");();
    execute!(std::io::stdout(), EnterAlternateScreen, EnableMouseCapture).expect("must always be able to enter alt screen");
}

pub async fn run(
    global_state: Arc<GlobalState>,
    tx: tokio::sync::broadcast::Sender<ProcMessage>,
    trace_msg_broadcaster: tokio::sync::broadcast::Sender<OddBoxEvent>,
    reloadable_filter : tracing_subscriber::reload::Layer<EnvFilter, tracing_subscriber::layer::Layered<crate::logging::TuiLoggerLayer, tracing_subscriber::Registry>>,
) {

    let log_buffer = Arc::new(Mutex::new(SharedLogBuffer::new()));
    let layer = crate::logging::TuiLoggerLayer { log_buffer: log_buffer.clone(), broadcaster: trace_msg_broadcaster };
    
    let reloadable_filter_handle = reloadable_filter.handle();

    let subscriber = tracing_subscriber::registry()
       .with(layer).with(reloadable_filter);

    tracing::subscriber::set_global_default(subscriber).expect("Failed to set collector");
  

    let backend = CrosstermBackend::new(std::io::stdout());
    
    let terminal = Terminal::new(backend).expect("must be possible to create terminal");
    
    let terminal = Arc::new(tokio::sync::Mutex::new(terminal));
    

    let mut manually_selected_theme : Option<dark_light::Mode> = None;
    
    let dark_style = dark_theme();
    let light_style = light_theme();


    let disabled_items : Vec<String> =  global_state.config.read().await.hosted_process.iter().flatten().filter_map( |x| 
      if x.auto_start.unwrap_or_default() { 
        Some(x.host_name.clone()) 
      } else {
        None
      }
    ).collect();

    
    tracing::info!("odd-box started successfully");
    
    // TUI event loop
    let tui_handle = {
        let terminal = Arc::clone(&terminal);
        let state = global_state.clone();
        let tx = tx.clone();
        task::spawn(async move {

            let mut theme = match dark_light::detect() {
                dark_light::Mode::Dark => Theme::Dark(dark_style),
                dark_light::Mode::Light => Theme::Light(light_style),
                dark_light::Mode::Default => Theme::Dark(dark_style),
            };

            let mut last_set_log_level_by_tui = tracing::level_filters::LevelFilter::TRACE;

            let mut count = 0;
            
            let tx = tx.clone();
           
            let mut tui_state = crate::types::tui_state::TuiState::new();
            
            loop {

                tui_state.log_level = LevelFilter::current().to_string();
                
                if count > 100 && manually_selected_theme.is_none() {
                    theme = match dark_light::detect() {
                        dark_light::Mode::Dark => Theme::Dark(dark_style),
                        dark_light::Mode::Light => Theme::Light(light_style),
                        dark_light::Mode::Default => Theme::Dark(dark_style)
                    };
                    count = 0;
                
                }
                
                // KEEP LOCK SHORT TO AVOID DEADLOCK
                {
                    let mut terminal = terminal.lock().await;
                    terminal.draw(|f| 
                        draw_ui::<CrosstermBackend<Stdout>>(
                            f,
                            global_state.clone(),
                            &mut tui_state,
                            &log_buffer,
                            &theme
                        )
                    )?;
                        
                }
                
            
                if global_state.app_state.exit.load(std::sync::atomic::Ordering::SeqCst) == true {
                    if global_state.app_state.site_status_map.iter().find(|x|
                            x.value() == &ProcState::Stopping 
                        || x.value() == &ProcState::Running
                        || x.value() == &ProcState::Starting 
                        
                    ).is_none() {
                        break; // nothing is running,stopping or starting.. we can exit now
                    }
                }
            
                if let Ok(true) = event::poll(std::time::Duration::from_millis(100)) {
                    
                    let (current_page,site_list_state) = {
                        (tui_state.current_page.clone(),tui_state.app_window_state.clone())
                    };
                    
                    let evt = event::read()?;
                
                   
                    match evt {
                        Event::Key(KeyEvent { 
                            code: crossterm::event::KeyCode::Char(' '),
                            modifiers: KeyModifiers::NONE,
                            kind: _, 
                            state:_ 
                        }) if tui_state.current_page==Page::Logs => {
                            
                            let mut buf = log_buffer.lock().expect("must always be able to lock log buffer");
                            buf.pause = !buf.pause;
                            let paused = buf.pause;
                            buf.logs.push_back(LogMsg {
                                msg: if paused { 
                                    format!("LOGGING PAUSED! PRESS SPACE TO RESUME.") 
                                } else {
                                    format!("LOGGING RESUMED! PRESS SPACE TO PAUSE.") 
                                },
                                lvl: Level::WARN,
                                src: String::from(""),
                                thread: Some(String::from("odd_box::tracing")),
                            });
                        }
                        Event::Key(KeyEvent { 
                            code: crossterm::event::KeyCode::Char('c'),
                            modifiers: KeyModifiers::CONTROL,
                            kind: _, 
                            state:_ 
                        }) => {
                            state.app_state.exit.store(true, std::sync::atomic::Ordering::SeqCst);
                            break;
                        },
                        Event::Mouse(mouse) => {
                                
                                if TuiSiteWindowState::Hide != site_list_state  {
                                    match mouse.kind {
                                        event::MouseEventKind::Moved => {
                                            tui_state.sites_handle_mouse_hover(mouse.column,mouse.row);
                                        }
                                        event::MouseEventKind::Down(event::MouseButton::Left) => {
                                            tui_state.sites_handle_mouse_click(mouse.column,mouse.row,tx.clone(), &state.app_state.site_status_map)
                                        }
                                        _ => {}
                                    }
                                }
                                match current_page {
                                    Page::Statistics => {
                                        
                                    }
                                    Page::Logs => {
                                        match mouse.kind {                                            
                                            event::MouseEventKind::Drag(event::MouseButton::Left) => {                                                
                                                tui_state.log_tab_stage.scroll_state.handle_mouse_drag(mouse.column,mouse.row);
                                            }
                                            event::MouseEventKind::Moved => {
                                                tui_state.log_tab_stage.scroll_state.handle_mouse_move(mouse.column,mouse.row);
                                            }

                                            event::MouseEventKind::ScrollDown => {
                                                tui_state.log_tab_stage.scroll_state.scroll_down(Some(10));
                                            },
                                            event::MouseEventKind::ScrollUp => {
                                                tui_state.log_tab_stage.scroll_state.scroll_up(Some(10));
                                            },
                                            _ => {}
                                        }
                                    },
                                    Page::Threads => {
                                        match mouse.kind {
                                            event::MouseEventKind::Drag(event::MouseButton::Left) => {
                                                tui_state.threads_tab_state.scroll_state.handle_mouse_drag(mouse.column,mouse.row);
                                            }
                                            event::MouseEventKind::Moved => {
                                                tui_state.threads_tab_state.scroll_state.handle_mouse_move(mouse.column,mouse.row);
                                            }
                                            event::MouseEventKind::ScrollDown => {
                                                tui_state.threads_tab_state.scroll_state.scroll_down(Some(10));
                                            },
                                            event::MouseEventKind::ScrollUp => {
                                                tui_state.threads_tab_state.scroll_state.scroll_up(Some(10));
                                            },
                                            _ => {}
                                        }
                                    },
                                    Page::Connections => {
                                        match mouse.kind {
                                            event::MouseEventKind::Drag(event::MouseButton::Left) => {
                                                tui_state.connections_tab_state.scroll_state.handle_mouse_drag(mouse.column,mouse.row);
                                            }
                                            event::MouseEventKind::Moved => {
                                                tui_state.connections_tab_state.scroll_state.handle_mouse_move(mouse.column,mouse.row);
                                            }
                                            event::MouseEventKind::ScrollDown => {
                                                tui_state.connections_tab_state.scroll_state.scroll_down(Some(10));
                                            },
                                            event::MouseEventKind::ScrollUp => {
                                                tui_state.connections_tab_state.scroll_state.scroll_up(Some(10));
                                            },
                                            _ => {}
                                        }
                                    },
                                }
                                
                        }
                        Event::Key(key) => {

                                match key.code {
                                    KeyCode::Char('l') => {
                                        
                                        let handle = reloadable_filter_handle.clone();
                                        
                                        // we cannot use the current log level anymore as we set different levels for proc host and main app
                                        // thus we will instead save a local copy of the current log level and circle through the levels here.
                                        match last_set_log_level_by_tui {
                                            tracing::level_filters::LevelFilter::TRACE => {
                                                last_set_log_level_by_tui = tracing::level_filters::LevelFilter::INFO;
                                                _ = handle.reload(
                                                    EnvFilter::from_str("odd_box=info").unwrap()
                                                    // we always allow host processes to log anything - its controlled by site specific config
                                                    // and filtered in the host_proc logic. same with all levels below here.
                                                    .add_directive("odd_box::proc_host=trace".parse().expect("This directive should always work"))
                                                );
                                                tracing::info!("Switched log level to INFO");
                                            }
                                            tracing::level_filters::LevelFilter::INFO => {
                                                last_set_log_level_by_tui = tracing::level_filters::LevelFilter::WARN;
                                                _ = handle.reload(
                                                    EnvFilter::from_str("odd_box=warn").unwrap()
                                                    .add_directive("odd_box::proc_host=trace".parse().expect("This directive should always work"))
                                                );
                                                // use warn log as it is now the lowest visible log level
                                                tracing::warn!("Switched log level to WARN"); 
                                            }
                                            tracing::level_filters::LevelFilter::WARN => {
                                                last_set_log_level_by_tui = tracing::level_filters::LevelFilter::ERROR;
                                                _ = handle.reload(
                                                    EnvFilter::from_str("odd_box=error").unwrap()
                                                    .add_directive("odd_box::proc_host=trace".parse().expect("This directive should always work"))
                                                );
                                                // use error log as it is now the lowest visible log level
                                                tracing::error!("Switched log level to ERROR");
                                            }
                                            tracing::level_filters::LevelFilter::ERROR => {
                                                last_set_log_level_by_tui = tracing::level_filters::LevelFilter::DEBUG;
                                                _ = handle.reload(
                                                    EnvFilter::from_str("odd_box=debug").unwrap()
                                                    .add_directive("odd_box::proc_host=trace".parse().expect("This directive should always work"))
                                                );
                                                tracing::debug!("Switched log level to DEBUG");
                                            }
                                            tracing::level_filters::LevelFilter::DEBUG => {
                                                last_set_log_level_by_tui = tracing::level_filters::LevelFilter::TRACE;
                                                _ = handle.reload(
                                                    EnvFilter::from_str("odd_box=trace").unwrap()
                                                    .add_directive("odd_box::proc_host=trace".parse().expect("This directive should always work"))
                                                );
                                                tracing::trace!("Switched log level to TRACE");
                                            }
                                            x => {
                                                last_set_log_level_by_tui = tracing::level_filters::LevelFilter::INFO;
                                                _ = handle.reload(
                                                    EnvFilter::from_str("odd_box=info").unwrap()
                                                    .add_directive("odd_box::proc_host=trace".parse().expect("This directive should always work"))
                                                );
                                                tracing::info!("Switched log level to INFO from {x:?}");
                                            }
                                        }
                                        
                                    }
                                    KeyCode::Esc | KeyCode::Char('q')  => {
                                        {
                                            tracing::warn!("User requested exit");
                                            state.app_state.exit.store(true, std::sync::atomic::Ordering::SeqCst);
                                            break;
                                        }
                                        
                                    },
                                    KeyCode::Char('t') => {
                                        match manually_selected_theme {
                                            None => {
                                                // when switching from auto to manual theme, we will switch to the opposite of the current theme
                                                match theme {
                                                    Theme::Light(_) => {
                                                        manually_selected_theme = Some(dark_light::Mode::Dark);
                                                        theme = Theme::Dark(dark_style);
                                                    },
                                                    Theme::Dark(_) => {
                                                        manually_selected_theme = Some(dark_light::Mode::Light);
                                                        theme = Theme::Light(light_style);
                                                    },
                                                }
                                            } 
                                            Some(dark_light::Mode::Dark) => {
                                                manually_selected_theme = Some(dark_light::Mode::Light);
                                                theme = Theme::Light(light_style);
                                            },
                                            Some(dark_light::Mode::Light) => {
                                                manually_selected_theme = Some(dark_light::Mode::Dark);
                                                theme = Theme::Dark(dark_style);
                                            },                                                                                        
                                            _ => {},
                                        };
                                    },
                                    _ => {}
                                }
                                match current_page {
                                    Page::Threads => {
                                        match key.code {
                                            KeyCode::PageUp => {
                                                tui_state.threads_tab_state.scroll_state.scroll_up(Some(10));
                                            }
                                            KeyCode::PageDown => {
                                                tui_state.threads_tab_state.scroll_state.scroll_down(Some(10))
                                                
                                            },
                                            KeyCode::Up => {
                                                tui_state.threads_tab_state.scroll_state.scroll_up(None)
                                            }
                                            KeyCode::Down => {
                                                tui_state.threads_tab_state.scroll_state.scroll_down(None)
                                            }
                                            _ => {}
                                        }
                                    },
                                    Page::Logs => {
                                        match key.code {
                                            KeyCode::Enter => {
                                                tui_state.log_tab_stage.scroll_state.vertical_scroll = None;
                                                let mut buf = log_buffer.lock().expect("must always be able to lock log buffer");
                                                // immediate effect instead of waiting for next log item
                                                match buf.limit {
                                                    Some(x) => {
                                                        while buf.logs.len() > x {
                                                            buf.logs.pop_front();
                                                        }
                                                    },
                                                    None => {},
                                                }
                                                
                                            }    
                                            KeyCode::Up => {
                                                tui_state.log_tab_stage.scroll_state.scroll_up(Some(1));
                                            }
                                            KeyCode::Down => {
                                                tui_state.log_tab_stage.scroll_state.scroll_down(Some(1));
                                            }
                                            KeyCode::PageUp => {
                                                let scroll_count = tui_state.log_tab_stage.scroll_state.area_height.saturating_div(2);
                                                if scroll_count > 0 {
                                                    tui_state.log_tab_stage.scroll_state.scroll_up(Some(scroll_count));
                                                }
                                            }
                                            KeyCode::PageDown => {
                                                let scroll_count = tui_state.log_tab_stage.scroll_state.area_height.saturating_div(2);
                                                if scroll_count > 0 {
                                                    tui_state.log_tab_stage.scroll_state.scroll_down(Some(scroll_count));
                                                }
                                            },   
                                            KeyCode::Char('c') => {
                                                let mut buf = log_buffer.lock().expect("must always be able to lock log buffer");
                                                tui_state.log_tab_stage.scroll_state.total_rows = 0;
                                                tui_state.log_tab_stage.scroll_state.vertical_scroll = None;
                                                tui_state.log_tab_stage.scroll_state.vertical_scroll_state = tui_state.log_tab_stage.scroll_state.vertical_scroll_state.position(0);
                                                buf.logs.clear();
                                                
                                            }    
                                            _ => {}        
                                        }
                                    }
                                    Page::Statistics => {},
                                    Page::Connections => {
                                        match key.code {
                                            KeyCode::PageUp => {
                                                tui_state.connections_tab_state.scroll_state.scroll_up(Some(10));
                                            }
                                            KeyCode::PageDown => {
                                                tui_state.connections_tab_state.scroll_state.scroll_down(Some(10));
                                                
                                            },
                                            KeyCode::Up => {
                                                let scroll_count = tui_state.connections_tab_state.scroll_state.area_height.saturating_div(2);
                                                if scroll_count > 0 {
                                                    tui_state.connections_tab_state.scroll_state.scroll_up(None);
                                                }
                                            }
                                            KeyCode::Down => {
                                                tui_state.connections_tab_state.scroll_state.scroll_down(None);
                                            }
                                            _ => {}
                                        }
                                    },
                                }

                                match key.code {    
                                
                                    KeyCode::Char('1') => {
                                        tui_state.current_page = Page::Logs;
                                    }
                                    KeyCode::Char('2') => {
                                        tui_state.current_page = Page::Connections;
                                    }
                                    KeyCode::Char('3') => {
                                        tui_state.current_page = Page::Statistics;
                                    }
                                    KeyCode::Char('4') => {
                                        tui_state.current_page = Page::Threads;
                                    }
                                    KeyCode::BackTab | KeyCode::Left => {
                                        match tui_state.current_page {
                                            Page::Logs => tui_state.current_page = Page::Threads, 
                                            Page::Threads => tui_state.current_page = Page::Statistics, 
                                            Page::Statistics => tui_state.current_page = Page::Connections,
                                            Page::Connections => tui_state.current_page = Page::Logs
                                        }
                                    }
                                    KeyCode::Tab | KeyCode::Right => {
                                        match tui_state.current_page {
                                            Page::Logs => tui_state.current_page = Page::Connections, 
                                            Page::Connections => tui_state.current_page = Page::Statistics, 
                                            Page::Statistics => tui_state.current_page = Page::Threads,
                                            Page::Threads => tui_state.current_page = Page::Logs
                                        }
                                    }          
                                    KeyCode::Char('z') => {
                                        {
                                            for mut guard in global_state.app_state.site_status_map.iter_mut() {
                                                let (_k,state) = guard.pair_mut();
                                                match state {
                                                    ProcState::Faulty =>  *state = ProcState::Stopping,
                                                    ProcState::Running =>  *state = ProcState::Stopping,
                                                    _ => {}
                                                }
                                            }
                                        }
                                        tx.clone().send(ProcMessage::StopAll).expect("must always be able to send internal messages");
                                    } 
                                    KeyCode::Char('s') => {
                                        {
                                            for mut guard in global_state.app_state.site_status_map.iter_mut() {
                                                let (_k,state) = guard.pair_mut();
                                                if disabled_items.contains(_k) {
                                                    continue;
                                                }
                                                if let ProcState::Running = state {
                                                    *state = ProcState::Starting;
                                                }
                                            }
                                        }
                                        tx.clone().send(ProcMessage::StartAll).expect("must always be able to send internal messages");
                                    }    
                                    KeyCode::Char('a') => {
                                        tui_state.app_window_state = tui_state.app_window_state.next()
                                    }                                  
                                    
                                    _ => {
    
                                    }
                            }
                            

                            // }


                            
                        },
                        _=> {}
                    }
                        
                }
            
            
                    
                
            } 
            Result::<(), std::io::Error>::Ok(())
        })
        
    };

    _ = tui_handle.await.ok();

    _ = disable_raw_mode().ok();
    let mut stdout = std::io::stdout();
    execute!(stdout, LeaveAlternateScreen, DisableMouseCapture).expect("should always be possible to leave tui");

    println!("odd-box tui thread exited.")
  
}



/// Returns a `Style` configured for a dark theme.
fn dark_theme() -> Style {
    Style::default()
        .fg(Color::White) // Text color
        //.bg(Color::Black) // Background color
        .add_modifier(Modifier::BOLD) // Text modifier
}

/// Returns a `Style` configured for a light theme.
fn light_theme() -> Style {
    Style::default()
        .fg(Color::Black) // Text color
        //.bg(Color::White) // Background color
        .add_modifier(Modifier::BOLD) // Text modifier
}

#[derive(Clone)]
pub enum Theme {
    Light(Style),
    Dark(Style)
}
impl Theme {
    fn inner_cloned(&self) -> Style {
        match self {
            Theme::Light(x) => *x,
            Theme::Dark(x) => *x,
        }
    }
}

fn draw_ui<B: ratatui::backend::Backend>(
    f: &mut ratatui::Frame, 
    global_state: Arc<GlobalState>,
    tui_state: &mut TuiState,
    log_buffer: &Arc<Mutex<SharedLogBuffer>>, 
    theme: &Theme,
) {


    let size = f.area();

    if size.height < 10 || size.width < 10 {
        return
    }

    let help_bar_height = 3 as u16;

    let constraints = if size.height < 15 {
        vec![
            Constraint::Min(1), // MAIN SECTION
            Constraint::Max(0),  
            Constraint::Length(help_bar_height), // QUICK BAR
        ]
    } else {
        match tui_state.app_window_state{
            TuiSiteWindowState::Hide => vec![
                Constraint::Percentage(100),
                Constraint::Max(0),  
                Constraint::Length(help_bar_height),
            ],
            TuiSiteWindowState::Small => vec![
                Constraint::Percentage(70),
                Constraint::Min(5),  
                Constraint::Length(help_bar_height), 
            ],
            TuiSiteWindowState::Medium => vec![
                Constraint::Percentage(60),
                Constraint::Min(5),  
                Constraint::Length(help_bar_height),
            ],
            TuiSiteWindowState::Large => vec![
                Constraint::Percentage(50),
                Constraint::Min(5),  
                Constraint::Length(help_bar_height),
            ]
        }
};

    let vertical = Layout::vertical(constraints);
    let [top_area, mid_area, bot_area] = vertical.areas(size);

    let main_area = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(100) 
        ])
        .split(top_area.clone()); 

    let is_dark_theme = matches!(&theme,Theme::Dark(_));
    
    let app_bg = {
        if is_dark_theme {
            Color::Reset
        } else {
            Color::White
        }
    };
    let tab_fg_color = if is_dark_theme {
        Color::Cyan
    } else {
        Color::DarkGray
    };

    let tabs =  ratatui::widgets::Tabs::new(
        vec![
             ratatui::text::Span::styled("[1] Logs", Style::default().fg(tab_fg_color)),
             ratatui::text::Span::styled("[2] Connections",Style::default().fg(tab_fg_color)),
             ratatui::text::Span::styled("[3] Stats",Style::default().fg(tab_fg_color)),
             ratatui::text::Span::styled("[4] Threads", Style::default().fg(tab_fg_color))
        ]).highlight_style(
            if is_dark_theme {
                Style::new().fg(Color::LightYellow)
            } else {
                Style::new().fg(Color::Black)
            }
        )
        .select(match tui_state.current_page {
            Page::Logs => 0,
            Page::Connections => 1,
            Page::Statistics => 2,
            Page::Threads => 3
        }) 
        
        .divider(ratatui::text::Span::raw("|"));

    

    let frame_margin = Margin { horizontal: 1, vertical: 1 };
        
    match tui_state.current_page {
        Page::Logs => logs_widget::draw(f,global_state.clone(),tui_state,log_buffer,main_area[0].inner(frame_margin),&theme),
        Page::Statistics => stats_widget::draw(f,global_state.clone(),tui_state,main_area[0].inner(frame_margin),&theme),
        Page::Connections => connections_widget::draw(f,global_state.clone(),tui_state,main_area[0].inner(frame_margin),&theme),
        Page::Threads => threads_widget::draw(f,global_state.clone(),tui_state,main_area[0].inner(frame_margin),&theme)
    }

    let frame = 
        Block::new()
        .border_style(
            if is_dark_theme {
                Style::new().fg(Color::DarkGray)
            } else {
                Style::new().fg(Color::DarkGray)
            }
            
        )
        .border_type(BorderType::Rounded)
        .borders(Borders::ALL);

    f.render_widget(frame.bg(app_bg), main_area[0]);
    

    // render the tab bar on top of the tab content
    f.render_widget(tabs.bg(app_bg), main_area[0].inner(Margin { horizontal: 2, vertical: 0 }));

    if size.height >= 15 && TuiSiteWindowState::Hide != tui_state.app_window_state {

        let sites_area_height = mid_area.height.saturating_sub(2);
        if sites_area_height == 0 {
            return
        }
        let sites_count = global_state.app_state.site_status_map.iter().count();
        let columns_needed = ((sites_count as f32 / sites_area_height as f32).ceil()).max(1.0) as usize;

        let site_columns = Layout::default()
            .direction(Direction::Horizontal)
            .flex(ratatui::layout::Flex::Legacy)
            .constraints(vec![Constraint::Percentage(100 / columns_needed as u16); columns_needed])
            .split(mid_area);

        let mut site_rects = vec![];

        for (col_idx, col) in site_columns.iter().enumerate() {
            
            let mut procly : Vec<(String, ProcState)> = global_state.app_state.site_status_map.iter()
                .map(|x|{
                    let (a,b) = x.pair();
                    (a.to_string(),b.to_owned())
                }).collect();

            procly.sort_by_key(|k| k.0.clone());
            
            let start_idx = col_idx * sites_area_height as usize;
            let end_idx = ((col_idx + 1) * sites_area_height as usize).min(sites_count);
            let items: Vec<ListItem> = procly[start_idx..end_idx].iter().enumerate().map(|(index,(id, state))| {
                
                let item_rect = ratatui::layout::Rect {
                    x: col.x,
                    y: col.y + index as u16 + 1,  // Assuming each ListItem is one line high
                    width: col.width,
                    height: 1,  // Assuming each ListItem is one line high
                };
                
                site_rects.push((item_rect,id.to_string()));

                let mut s = match state {
                    &ProcState::Running => Style::default().fg(
                        if is_dark_theme {
                            Color::LightGreen
                        } else {
                            Color::Green
                        }
                    ),
                    &ProcState::Faulty => Style::default().fg(
                        if is_dark_theme {
                                Color::LightMagenta
                            } else {
                                Color::Black
                            }
                    ),
                    &ProcState::Starting => Style::default().fg(
                        if is_dark_theme {
                                Color::LightGreen
                            } else {
                                Color::Green
                            }
                    ),
                    &ProcState::Stopped => Style::default().fg(
                        if is_dark_theme{
                                Color::DarkGray
                            } else {
                                Color::DarkGray
                            }
                    ),
                    &ProcState::Stopping => Style::default().fg(
                        if is_dark_theme {
                                Color::Cyan
                            } else {
                                Color::Black
                            }
                    ),
                    &ProcState::Remote => Style::default().fg(
                        if is_dark_theme {
                                Color::Cyan
                            } else {
                                Color::Blue
                            }
                    ),
                    &ProcState::DirServer => Style::default().fg(
                        if is_dark_theme {
                                Color::Cyan
                            } else {
                                Color::Cyan
                            }
                    ),
                    &ProcState::Docker => Style::default().fg(
                        if is_dark_theme {
                                Color::LightMagenta
                            } else {
                                Color::Magenta
                            }
                    ),
                };

                let mut id_style = theme.inner_cloned();
                if let Some(hovered) = &tui_state.currently_hovered_site {
                    if hovered == id {
                        id_style = id_style.add_modifier(Modifier::BOLD);
                        s = if is_dark_theme { s.bg(Color::Gray) } else { s.bg(Color::Gray) };
                    } 
                }
            
                
                let message = ratatui::text::Span::styled(format!(" {id} "),
                    id_style);

                let status = match state {
                    &ProcState::Running => ratatui::text::Span::styled(format!(" {:?}",state),s),
                    &ProcState::Faulty => ratatui::text::Span::styled(format!(" {state:?} (retrying in 5s)"),s),
                    &ProcState::Starting => ratatui::text::Span::styled(format!(" {:?}",state),s),
                    &ProcState::Stopped => ratatui::text::Span::styled(format!(" {:?}",state),s),
                    &ProcState::Stopping => ratatui::text::Span::styled(format!(" {:?}..",state),s),
                    &ProcState::Remote => ratatui::text::Span::styled(format!(" {:?}",state),s),
                    &ProcState::DirServer => ratatui::text::Span::styled(format!(" {:?}",state),s),
                    &ProcState::Docker => ratatui::text::Span::styled(format!(" {:?}",state),s)
                    
                    
                };

                ListItem::new(Line::from(vec![
                    message,
                    status
                ]))
                
            }).collect();

            let sites_list = List::new(items)
                .block( 
                    Block::new()
                        .border_style(Style::default().fg(Color::DarkGray))
                        .border_type(BorderType::Rounded)
                        .borders(Borders::ALL)
                        .title(" Sites ").title_alignment(Alignment::Left)
                        .title_style(
                            if is_dark_theme {
                                Style::default().fg(Color::Cyan)
                            } else {
                                Style::default().fg(Color::Blue)
                            }
                        )
                );
            
            f.render_widget(sites_list.bg(app_bg), *col);
            
        }

        tui_state.site_rects = site_rects;
    }

    
      
    let help_bar_chunk = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(0),
            Constraint::Length(3) 
        ])
        .split(bot_area.clone()); 


    
    let mut help_bar_text = vec![
        ratatui::text::Span::raw("q: Quit | "),
        ratatui::text::Span::raw("a: Tgl Sites | "),
    ];


    help_bar_text.push(ratatui::text::Span::raw("s: Start all | "));
    help_bar_text.push(ratatui::text::Span::raw("z: Stop all | "));

    help_bar_text.push(ratatui::text::Span::raw("↑/↓: Scroll | "));

    if Page::Logs == tui_state.current_page {
        help_bar_text.push(ratatui::text::Span::raw("c: CLS | "));
        help_bar_text.push(ratatui::text::Span::raw("tab: Nxt tab "));
        if tui_state.log_tab_stage.scroll_state.vertical_scroll.is_some() {
            help_bar_text.push(ratatui::text::Span::raw("| rtrn: Tail "));
        }
        help_bar_text.push(ratatui::text::Span::raw("| space: Un/Paus log "));
        help_bar_text.push(ratatui::text::Span::raw("| l: LogLvl"));
    } else {
        help_bar_text.push(ratatui::text::Span::raw("| tab: Tgl page "));
    }

    help_bar_text.push(ratatui::text::Span::raw("| t: theme"));

    // // DEBUG
    // help_bar_text.push(ratatui::text::Span::raw(format!("| DBG: {}", 
    //     app_state.dbg
    // )));
    let current_version = self_update::cargo_crate_version!();
    let help_bar = Paragraph::new(Line::from(help_bar_text))
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center)
        .block(Block::default().borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::DarkGray))
        .title(format!(" ODD-BOX v{current_version}")).title_style(
            if is_dark_theme {
                Style::default().fg(Color::LightYellow)
            } else {
                Style::default().fg(Color::Black)
            }
        ));

    f.render_widget(help_bar.bg(app_bg), help_bar_chunk[1]);


}

fn wrap_string(input: &str, max_length: usize) -> Vec<String> {
    let words = input.split_whitespace();
    let mut wrapped_lines = Vec::new();
    let mut current_line = String::new();

    for word in words {
        if word.len() <= max_length {
            if !current_line.is_empty() {
                if current_line.len() + 1 + word.len() > max_length {
                    wrapped_lines.push(current_line);
                    current_line = String::new();
                } else {
                    current_line.push(' ');
                }
            }
            current_line.push_str(word);
        } else {
            if !current_line.is_empty() {
                wrapped_lines.push(current_line);
                current_line = String::new();
            }
            let chunks = split_string_into_chunks(word, max_length);
            for chunk in chunks {
                wrapped_lines.push(chunk);
            }
        }
    }

    // Add any remaining text
    if !current_line.is_empty() {
        wrapped_lines.push(current_line);
    }

    wrapped_lines
}

fn split_string_into_chunks(s: &str, chunk_size: usize) -> Vec<String> {
    let mut chunks = Vec::new();
    let mut start = 0;

    while start < s.len() {
        let end = if start + chunk_size > s.len() {
            s.len()
        } else {
            let mut end = start + chunk_size;
            while !s.is_char_boundary(end) {
                end -= 1;
            }
            end
        };
        chunks.push(s[start..end].to_string());
        start = end;
    }

    chunks
}