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
use std::{sync::Arc, time::Duration};

use cache::CardCache;
use card::SavedCard;
use filter::FilterUtil;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use uuid::Uuid;

pub mod cache;
pub mod card;
pub mod categories;
pub mod common;
pub mod config;
pub mod filter;
pub mod git;
pub mod media;
//pub mod ml;
//pub mod openai;

pub enum CardsAction {
    Review,
    SetSuspended(bool),
}

#[derive(Default, Clone)]
enum Field {
    _Strength,
    #[default]
    LastModified,
}

#[derive(Default, Clone)]
struct CardSorter {
    ascending: bool,
    field: Field,
}

#[derive(Clone)]
enum Mode {
    List { index: usize },
    View { index: usize },
}

impl Mode {
    fn toggle(&mut self) {
        *self = match self {
            Self::List { index } => Self::View { index: *index },
            Self::View { index } => Self::List { index: *index },
        }
    }

    fn is_view(&self) -> bool {
        match self {
            Mode::List { .. } => false,
            Mode::View { .. } => true,
        }
    }

    fn is_list(&self) -> bool {
        !self.is_view()
    }

    fn enter_list(&mut self) {
        let index = self.idx();
        *self = Self::List { index };
    }
    fn enter_view(&mut self) {
        let index = self.idx();
        *self = Self::View { index };
    }

    fn idx(&self) -> usize {
        match self {
            Mode::List { index } => *index,
            Mode::View { index } => *index,
        }
    }

    fn mut_idx(&mut self) -> &mut usize {
        match self {
            Mode::List { index } => index,
            Mode::View { index } => index,
        }
    }

    pub fn set_idx(&mut self, idx: usize) {
        *self.mut_idx() = idx;
    }
}

impl Default for Mode {
    fn default() -> Self {
        Self::List { index: 0 }
    }
}

/// Struct meant for viewing cards, sort of a wrapper around FilterUtil.
#[derive(Clone)]
pub struct CardViewer {
    cards: Vec<Id>,
    filtered_cards: Vec<Id>,
    filter: FilterUtil,
    sorter: CardSorter,
    mode: Mode,
}

impl CardViewer {
    pub fn new(cards: Vec<Id>) -> Self {
        if cards.is_empty() {
            panic!("plz at least one element");
        }

        Self {
            cards: cards.clone(),
            filtered_cards: cards,
            filter: FilterUtil::default(),
            sorter: CardSorter::default(),
            mode: Mode::default(),
        }
    }

    pub fn total_qty(&self) -> usize {
        self.cards.len()
    }

    pub fn set_idx(&mut self, idx: usize) {
        self.mode.set_idx(idx);
    }

    pub fn filtered_qty(&self) -> usize {
        self.filtered_cards.len()
    }

    fn update_filtered_cards(&mut self, mut cards: Vec<Id>, cache: &mut CardCache) {
        match self.sorter.field {
            Field::_Strength => {
                cards.sort_by_key(|card| cache.get_ref(*card).strength().unwrap_or_default())
            }
            Field::LastModified => cards.sort_by_key(|card| cache.get_ref(*card).last_modified()),
        }
        if !self.sorter.ascending {
            cards.reverse();
        }
        self.filtered_cards = cards;
    }

    pub fn go_forward(&mut self) {
        let card_len = self.filtered_cards.len();
        let idx = self.mode.mut_idx();

        if *idx < card_len - 1 {
            *idx += 1;
        }
    }

    pub fn filtered_cards(&self) -> &Vec<Id> {
        &self.filtered_cards
    }

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

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

    pub fn filter_ref(&self) -> &FilterUtil {
        &self.filter
    }

    pub fn enter_view(&mut self) {
        self.mode.enter_view();
    }

    pub fn enter_list(&mut self) {
        self.mode.enter_list();
    }

    pub fn idx(&self) -> usize {
        self.mode.idx()
    }

    pub fn selected_card_id(&self) -> Id {
        self.filtered_cards[self.idx()]
    }

    pub fn selected_card(&self, cache: &mut CardCache) -> Arc<SavedCard> {
        let idx = self.mode.idx();
        cache.get_ref(self.filtered_cards[idx])
    }

    pub fn go_back(&mut self) {
        let idx = self.mode.mut_idx();

        if *idx > 0 {
            *idx -= 1;
        }
    }

    pub fn filter_mut(&mut self) -> &mut FilterUtil {
        &mut self.filter
    }

    pub fn re_apply_rules(&mut self, cache: &mut CardCache) {
        let cards = self.filter.evaluate_cards(self.cards.clone(), cache);

        if !cards.is_empty() {
            self.filtered_cards = cards;
        }
    }

    pub fn filter(mut self, filter: FilterUtil, cache: &mut CardCache) -> Self {
        let filtered_cards = filter.evaluate_cards(self.cards.clone(), cache);
        if filtered_cards.is_empty() {
            return self;
        }
        self.update_filtered_cards(filtered_cards, cache);
        self.filter = filter;
        *self.mode.mut_idx() = 0;
        self
    }

    pub fn toggle_mode(&mut self) {
        self.mode.toggle();
    }
}

pub mod paths {
    use std::path::PathBuf;

    pub fn get_import_csv() -> PathBuf {
        get_share_path().join("import.csv")
    }

    pub fn get_cards_path() -> PathBuf {
        get_share_path().join("cards")
    }

    pub fn get_ml_path() -> PathBuf {
        get_share_path().join("ml/")
    }

    pub fn get_runmodel_path() -> PathBuf {
        get_ml_path().join("runmodel.py")
    }

    pub fn get_media_path() -> PathBuf {
        get_share_path().join("media/")
    }

    #[cfg(not(test))]
    pub fn get_share_path() -> PathBuf {
        let home = dirs::home_dir().unwrap();
        home.join(".local/share/speki/")
    }

    #[cfg(test)]
    pub fn get_share_path() -> PathBuf {
        PathBuf::from("./test_dir/")
    }
}

pub type Id = Uuid;

pub fn duration_to_days(dur: &Duration) -> f32 {
    dur.as_secs_f32() / 86400.
}

pub fn days_to_duration(days: f32) -> Duration {
    Duration::from_secs_f32(days * 86400.)
}

pub fn serialize_duration<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let days = duration.as_ref().map(duration_to_days);
    days.serialize(serializer)
}

pub fn deserialize_duration<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
where
    D: Deserializer<'de>,
{
    let days = Option::<f32>::deserialize(deserializer)?;
    Ok(days.map(days_to_duration))
}