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
pub mod actions;
pub mod state;
pub mod ui;

use crate::{
    app::{
        actions::{Action, Actions},
        state::AppState,
    },
    inputs::key::Key,
    io::IoEvent,
    utils::ImageMode,
};

#[derive(Debug, PartialEq, Eq)]
pub enum AppReturn {
    Exit,
    Continue,
}

#[derive(Debug, Clone)]
pub struct AppConfig {
    pub image_mode: ImageMode,
}

#[derive(Clone)]
pub struct App<'a> {
    io_tx: tokio::sync::mpsc::Sender<IoEvent>,
    actions: Actions,
    is_loading: bool,
    pub state: AppState<'a>,
    pub config: AppConfig,
}

impl<'a> App<'a> {
    pub fn new(io_tx: tokio::sync::mpsc::Sender<IoEvent>, image_mode: ImageMode) -> Self {
        let actions = vec![Action::Quit].into();
        let is_loading = false;
        let state = AppState::default();
        let config = AppConfig { image_mode };

        Self {
            io_tx,
            actions,
            is_loading,
            state,
            config,
        }
    }

    pub async fn do_action(&mut self, key: Key) -> AppReturn {
        if let Some(action) = self.actions.find(key) {
            match action {
                Action::Quit => AppReturn::Exit,
                Action::Increment => {
                    self.state.increment_index();
                    AppReturn::Continue
                }
                Action::Decrement => {
                    self.state.decrement_index();
                    AppReturn::Continue
                }
                Action::Show => {
                    self.dispatch(IoEvent::LoadImage).await;
                    AppReturn::Continue
                }
            }
        } else {
            AppReturn::Continue
        }
    }

    pub async fn update_on_tick(&mut self) -> AppReturn {
        AppReturn::Continue
    }

    pub async fn dispatch(&mut self, action: IoEvent) {
        self.is_loading = true;
        if self.io_tx.send(action).await.is_err() {
            self.is_loading = false;
        };
    }

    pub fn actions(&self) -> &Actions {
        &self.actions
    }

    pub fn state(&self) -> &AppState {
        &self.state
    }

    pub fn state_mut(&'a mut self) -> &'a mut AppState {
        &mut self.state
    }

    pub fn is_loading(&self) -> bool {
        self.is_loading
    }

    pub fn initialized(&mut self, path: &str) {
        self.actions = vec![
            Action::Quit,
            Action::Increment,
            Action::Decrement,
            Action::Show,
        ]
        .into();
        self.state = AppState::initialized(path);
    }

    pub fn loaded(&mut self) {
        self.is_loading = false;
    }
}