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
use std::path::PathBuf;

use crossterm::event::KeyEvent;
use leetcode_tui_db::{DbQuestion, DbTopic};
use leetcode_tui_shared::RoCell;

use tokio::sync::{mpsc::UnboundedSender, oneshot};

static TX: RoCell<UnboundedSender<Event>> = RoCell::new();

pub enum Event {
    Quit,
    Key(KeyEvent),
    Render(String),
    Resume,
    Suspend,
    Resize(u16, u16),
    Topic(DbTopic),
    Questions(Vec<DbQuestion>),
    QuestionFilter(Option<String>),
    Popup(Option<String>, Vec<String>),
    SelectPopup(
        Option<String>,
        Vec<String>,
        tokio::sync::oneshot::Sender<Option<usize>>,
    ),
    Input(super::UBStrSender, Option<String>),
    Open(PathBuf),
    Error(String),
    QuestionUpdate,
}

impl Event {
    #[inline]
    pub fn init(tx: UnboundedSender<Event>) {
        TX.init(tx);
    }

    #[inline]
    pub fn emit(self) {
        TX.as_ref().send(self).ok();
    }

    pub async fn wait<T>(self, rx: oneshot::Receiver<T>) -> T {
        TX.as_ref().send(self).ok();
        rx.await.unwrap_or_else(|_| std::process::exit(0))
    }
}

#[macro_export]
macro_rules! emit {
    (Key($key:expr)) => {
        $crate::Event::Key($key).emit();
    };
    (Render) => {
        $crate::Event::Render(format!("{}:{}", file!(), line!())).emit();
    };
    (Resize($cols:expr, $rows:expr)) => {
        $crate::Event::Resize($cols, $rows).emit();
    };
    (Topic($topic:expr)) => {
        $crate::Event::Topic($topic).emit();
    };
    (Questions($questions:expr)) => {
        $crate::Event::Questions($questions).emit();
    };
    (Popup($lines:expr)) => {
        $crate::Event::Popup(None, $lines).emit();
    };
    (Popup($title:expr, $lines:expr)) => {
        $crate::Event::Popup(Some($title.into()), $lines).emit();
    };
    (SelectPopup($a: expr)) => {{
        let (tx, rx) = tokio::sync::oneshot::channel();
        $crate::Event::SelectPopup(None, $a, tx).wait(rx)
    }};
    (SelectPopup($title:expr, $a: expr)) => {{
        let (tx, rx) = tokio::sync::oneshot::channel();
        $crate::Event::SelectPopup(Some($title.into()), $a, tx).wait(rx)
    }};
    (Error($e:expr)) => {
        $crate::Event::Error($e).emit();
    };
    (Open($e:expr)) => {
        $crate::Event::Open($e).emit();
    };
    (Input($e:expr)) => {{
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        $crate::Event::Input(tx, $e).emit();
        rx
    }};
    (QuestionFilter($e:expr)) => {
        $crate::Event::QuestionFilter($e).emit();
    };
    ($event:ident) => {
        $crate::Event::$event.emit();
    };
}