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
use crate::{
    app_ui::{
        async_task_channel::{
            ChannelRequestSender, Request as TaskRequestFormat, Response, TaskRequest, TaskResponse,
        },
        components::{color::TokyoNightColors, help_text::CommonHelpText, list::StatefulList},
        widgets::question_list::custom_lists::NEETCODE_75,
    },
    entities::TopicTagModel,
    errors::AppResult,
};

use crossterm::event::KeyEvent;
use ratatui::{
    prelude::*,
    widgets::{Block, Borders, List, ListItem},
};

use super::{
    notification::{
        NotifContent, Notification,
        WidgetName::{self, QuestionList},
    },
    CommonState, CommonStateManager, CrosstermStderr, Widget,
};
use crate::app_ui::components::color::Callout;

#[derive(Debug)]
pub struct TopicTagListWidget {
    common_state: CommonState,
    pub topics: StatefulList<TopicTagModel>,
}

impl TopicTagListWidget {
    pub fn new(id: WidgetName, task_sender: ChannelRequestSender) -> Self {
        Self {
            common_state: CommonState::new(
                id,
                task_sender,
                vec![
                    CommonHelpText::ScrollUp.into(),
                    CommonHelpText::ScrollDown.into(),
                    CommonHelpText::SwitchPane.into(),
                ],
            ),
            topics: Default::default(),
        }
    }
}

impl TopicTagListWidget {
    fn get_item(ttm: &TopicTagModel) -> ListItem {
        ListItem::new(Text::styled(ttm.name.clone(), Style::default()))
    }

    fn update_questions(&mut self) -> AppResult<Option<Notification>> {
        if let Some(topic_tag) = self.topics.get_selected_item() {
            let questions = vec![topic_tag.clone()];
            let notif = Notification::Questions(NotifContent::new(
                WidgetName::TopicList,
                QuestionList,
                questions,
            ));
            return Ok(Some(notif));
        }
        Ok(None)
    }
}

super::impl_common_state!(
    TopicTagListWidget,
    fn set_active(&mut self) -> AppResult<Option<Notification>> {
        self.common_state.active = true;
        Ok(Some(Notification::HelpText(NotifContent::new(
            WidgetName::TopicList,
            WidgetName::HelpLine,
            self.get_help_texts().clone(),
        ))))
    }
);

impl Widget for TopicTagListWidget {
    fn render(&mut self, rect: Rect, frame: &mut CrosstermStderr) {
        let lines = self
            .topics
            .items
            .iter()
            .map(Self::get_item)
            .collect::<Vec<_>>();

        let mut border_style = Style::default();

        if self.is_active() {
            border_style = border_style.fg(TokyoNightColors::Pink.into());
        }

        let hstyle: Style = Callout::Info.into();
        let items = List::new(lines)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Topics")
                    .border_style(border_style),
            )
            .highlight_style(
                hstyle
                    .add_modifier(Modifier::BOLD)
                    .fg(TokyoNightColors::Pink.into())
                    .bg(TokyoNightColors::Selection.into()),
            );
        frame.render_stateful_widget(items, rect, &mut self.topics.state);
    }

    fn handler(&mut self, event: KeyEvent) -> AppResult<Option<Notification>> {
        match event.code {
            crossterm::event::KeyCode::Up => {
                self.topics.previous();
                return self.update_questions();
            }
            crossterm::event::KeyCode::Down => {
                self.topics.next();
                return self.update_questions();
            }
            _ => {}
        };
        Ok(None)
    }

    fn process_task_response(&mut self, response: TaskResponse) -> AppResult<()> {
        if let TaskResponse::AllTopicTags(Response { content, .. }) = response {
            self.topics.add_item(TopicTagModel {
                name: "All".to_owned(),
                id: "all".to_owned(),
                slug: "all".to_owned(),
            });
            self.topics.add_item(NEETCODE_75.get_topic_tag());
            for tt in content {
                self.topics.add_item(tt)
            }
        }
        self.update_questions()?;
        Ok(())
    }

    fn setup(&mut self) -> AppResult<()> {
        self.get_task_sender()
            .send(TaskRequest::GetAllTopicTags(TaskRequestFormat {
                widget_name: self.get_widget_name(),
                request_id: "".to_string(),
                content: (),
            }))
            .map_err(Box::new)?;
        Ok(())
    }
}