aboutsummaryrefslogtreecommitdiff
path: root/src/gui/update.rs
blob: 7b3625c86f9cd083ac99f3eb727ced2876159872 (plain)
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
use async_channel::{Receiver, Sender};
use chrono::{Duration, NaiveDate};
use gtk4::prelude::GridExt;
use std::collections::HashSet;
use std::iter::FromIterator;
use uuid::Uuid;

use crate::{
    db,
    gui::{calendar, form, utils, App},
    model::{event, event::Event},
};

pub fn send(tx: Sender<Msg>, msg: Msg) {
    utils::spawn(async move {
        let _ = tx.send(msg).await;
    })
}

pub enum Msg {
    ShowAddForm {
        date: NaiveDate,
    },
    ShowRepetitionDialog {
        event_id: Uuid,
        date: NaiveDate,
    },
    ShowUpdateForm {
        event_id: Uuid,
    },
    ShowUpdateRepetitionForm {
        event_id: Uuid,
        date: NaiveDate,
    },
    ShowUpdateFromOccurence {
        event_id: Uuid,
        date: NaiveDate,
    },
    AddEvent {
        new: Event,
    },
    UpdateEvent {
        old: Event,
        new: Event,
    },
    UpdateEventOccurence {
        event: Event,
        occurence: usize,
        date: NaiveDate,
        new: Event,
    },
    UpdateRepeatedFrom {
        old: Event,
        updated: Event,
        new: Event,
    },
    DeleteEvent {
        event: Event,
    },
    DeleteOccurence {
        event: Event,
        date: NaiveDate,
        occurence: usize,
    },
    SelectPreviousWeek,
    SelectNextWeek,
}

pub async fn event_handler(rx: Receiver<Msg>, mut app: App) {
    while let Ok(msg) = rx.recv().await {
        match msg {
            Msg::ShowAddForm { date } => form::show(&app, form::Target::New { date }).await,
            Msg::ShowRepetitionDialog { date, event_id } => {
                match app.recurring_events.iter().position(|e| e.id == event_id) {
                    Some(index) => {
                        form::repetition_dialog(&app, date, &app.recurring_events[index]).await
                    }
                    None => eprintln!("Event not found with id: {}", event_id),
                }
            }
            Msg::ShowUpdateForm { event_id } => {
                match app.recurring_events.iter().position(|e| e.id == event_id) {
                    Some(index) => {
                        form::show(
                            &app,
                            form::Target::Update {
                                event: app.recurring_events[index].clone(),
                            },
                        )
                        .await
                    }
                    None => match app.events.iter().position(|e| e.id == event_id) {
                        Some(index) => {
                            form::show(
                                &app,
                                form::Target::Update {
                                    event: app.events[index].clone(),
                                },
                            )
                            .await
                        }
                        None => eprintln!("Event not found with id: {}", event_id),
                    },
                }
            }
            Msg::ShowUpdateRepetitionForm { event_id, date } => {
                match app.recurring_events.iter().position(|e| e.id == event_id) {
                    Some(index) => {
                        form::show(
                            &app,
                            form::Target::UpdateRepetition {
                                date,
                                event: app.recurring_events[index].clone(),
                            },
                        )
                        .await
                    }
                    None => eprintln!("Event not found with id: {}", event_id),
                }
            }
            Msg::ShowUpdateFromOccurence { event_id, date } => {
                match app.recurring_events.iter().position(|e| e.id == event_id) {
                    Some(index) => {
                        let event = app.recurring_events[index].clone();
                        form::show(&app, form::Target::UpdateFromOccurence { date, event }).await
                    }
                    None => eprintln!("Event not found with id: {}", event_id),
                }
            }
            Msg::AddEvent { new } => {
                let refresh_dates = add(&mut app, &new);
                refresh(&app, &refresh_dates)
            }
            Msg::UpdateEvent { old, new } => {
                let mut refresh_dates = remove(&mut app, &old);
                refresh_dates.extend(add(&mut app, &new));
                refresh(&app, &refresh_dates);
            }
            Msg::UpdateEventOccurence {
                event,
                occurence,
                date,
                new,
            } => {
                remove_occurence(&mut app, &event, occurence);
                let mut refresh_dates = add(&mut app, &new);
                refresh_dates.insert(date);
                refresh(&app, &refresh_dates)
            }
            Msg::UpdateRepeatedFrom { old, updated, new } => {
                let mut refresh_dates = remove(&mut app, &old);
                refresh_dates.extend(add(&mut app, &updated));
                refresh_dates.extend(add(&mut app, &new));
                refresh(&app, &refresh_dates);
            }
            Msg::DeleteEvent { event } => {
                let refresh_dates = remove(&mut app, &event);
                refresh(&app, &refresh_dates)
            }
            Msg::DeleteOccurence {
                event,
                date,
                occurence,
            } => {
                remove_occurence(&mut app, &event, occurence);
                refresh(&app, &HashSet::from([date]))
            }
            Msg::SelectPreviousWeek => {
                app.calendar.remove_row(4);
                app.calendar.insert_row(1);
                app.start_date -= Duration::days(7);
                app.end_date -= Duration::days(7);

                match db::events::list_non_recurring_between(
                    &app.conn,
                    app.start_date,
                    app.end_date,
                ) {
                    Ok(events) => app.events = events,
                    Err(err) => eprintln!("{}", err),
                };
                refresh(&app, &HashSet::from_iter(week_from(app.start_date)));
            }
            Msg::SelectNextWeek => {
                app.calendar.remove_row(1);
                app.calendar.insert_row(4);
                app.start_date += Duration::days(7);
                app.end_date += Duration::days(7);

                match db::events::list_non_recurring_between(
                    &app.conn,
                    app.start_date,
                    app.end_date,
                ) {
                    Ok(events) => app.events = events,
                    Err(err) => eprintln!("{}", err),
                };
                refresh(
                    &app,
                    &HashSet::from_iter(week_from(app.end_date - Duration::days(6))),
                );
            }
        }
    }
}

/// Remove event and return dates  that should be refreshed.
fn remove(app: &mut App, event: &Event) -> HashSet<NaiveDate> {
    if event.repetition.is_some() {
        match app.recurring_events.iter().position(|e| e.id == event.id) {
            Some(index) => {
                app.recurring_events.remove(index);
                repetition_dates(app, event)
            }
            None => {
                eprintln!("Event not found when trying to delete {:?}", event);
                HashSet::new()
            }
        }
    } else {
        match app.events.iter().position(|e| e.id == event.id) {
            Some(index) => {
                app.events.remove(index);
                HashSet::from([event.date])
            }
            None => {
                eprintln!("Event not found when trying to delete {:?}", event);
                HashSet::new()
            }
        }
    }
}

/// Remove event repetition
/// TODO: Completely remove the event if it’s the last remaining occurence
fn remove_occurence(app: &mut App, event: &Event, occurence: usize) {
    match app.recurring_events.iter().position(|e| e.id == event.id) {
        Some(index) => {
            let event = app.recurring_events.get_mut(index).unwrap();
            match event.repetition.clone() {
                Some(mut repetition) => {
                    repetition.removed_occurences.insert(occurence);
                    event.repetition = Some(repetition.clone())
                }
                None => eprintln!(
                    "Repetition not found when trying to delete repetition of {:?}",
                    event
                ),
            }
        }
        None => {
            eprintln!(
                "Event not found when trying to delete repetition of {:?}",
                event
            )
        }
    }
}

/// Add event and return dates that should be refreshed.
fn add(app: &mut App, event: &Event) -> HashSet<NaiveDate> {
    if event.repetition.is_some() {
        app.recurring_events.push(event.clone());
        let mut dates = repetition_dates(app, event);
        dates.insert(event.date);
        dates
    } else {
        app.events.push(event.clone());
        HashSet::from([event.date])
    }
}

/// Repetition dates of a repetead event.
fn repetition_dates(app: &App, event: &Event) -> HashSet<NaiveDate> {
    let event_reps = event::repetitions_between(&[event.clone()], app.start_date, app.end_date);
    HashSet::from_iter(event_reps.keys().copied())
}

/// Refresh app for the given dates.
fn refresh(app: &App, dates: &HashSet<NaiveDate>) {
    let repetitions =
        event::repetitions_between(&app.recurring_events, app.start_date, app.end_date);

    for date in dates {
        if date >= &app.start_date && date <= &app.end_date {
            calendar::refresh_date(app, *date, &repetitions, &app.categories, &app.default_color)
        }
    }
}

/// Seven days vector from the given date.
fn week_from(date: NaiveDate) -> Vec<NaiveDate> {
    let mut res = vec![date];
    for i in 1..=6 {
        res.push(date + Duration::days(i))
    }
    res
}