use async_channel::{Receiver, Sender}; use chrono::NaiveDate; use crate::{ app::{calendar, form, utils, App}, model::{event, event::Event}, }; pub fn send(tx: Sender, msg: Msg) { utils::spawn(async move { let _ = tx.send(msg).await; }) } pub enum Msg { ShowAddForm { date: NaiveDate }, ShowUpdateForm { event: Event }, AddEvent { new: Event }, UpdateEvent { old: Event, new: Event }, DeleteEvent { event: Event }, } pub async fn event_handler(rx: Receiver, mut app: App) { while let Ok(msg) = rx.recv().await { match msg { Msg::ShowAddForm { date } => { form::show(&app, event::init(date), true).await; } Msg::ShowUpdateForm { event } => { form::show(&app, event, false).await; } Msg::AddEvent { new } => { let date = new.date.clone(); app.events.push(new); calendar::refresh_date(&app, date); } Msg::UpdateEvent { old, new } => { let new_date = new.date.clone(); match app.events.iter().position(|e| e.id == new.id) { Some(index) => { app.events.remove(index); app.events.push(new); calendar::refresh_date(&app, new_date); if old.date != new_date { calendar::refresh_date(&app, old.date.clone()) } } None => println!("Event not found when updating from {:?} to {:?}", old, new), } } Msg::DeleteEvent { event } => { match app.events.iter().position(|e| e.id == event.id) { Some(index) => { app.events.remove(index); calendar::refresh_date(&app, event.date); } None => println!("Event not found when trying to delete {:?}", event), } } } } }