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
use anyhow::Result;
use crossterm::event::Event;
use tui::{
    backend::Backend,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    Frame,
};

use super::LabelProcess;
use crate::{
    common::{
        widget::{
            CustomParagraph, CustomStatefulList, CustomStatefulWidget, CustomWidget, TextInput,
            DEFAULT_HIGHLIGHT_SYMBOL_PREFIX,
        },
        ExecutionContext, InteractiveProcess, Process,
    },
    model::{AsLabeledCommand, Command},
    storage::SqliteStorage,
    ProcessOutput,
};

/// Process to search for [Command]
pub struct SearchProcess<'s> {
    /// Storage
    storage: &'s SqliteStorage,
    /// Current value of the filter box
    filter: CustomParagraph<TextInput>,
    /// Command list of results
    commands: CustomStatefulList<Command>,
    /// Delegate label widget
    delegate_label: Option<LabelProcess<'s>>,
    // Execution context
    ctx: ExecutionContext,
}

impl<'s> SearchProcess<'s> {
    pub fn new(storage: &'s SqliteStorage, filter: String, ctx: ExecutionContext) -> Result<Self> {
        let commands = storage.find_commands(&filter)?;

        let filter = CustomParagraph::new(TextInput::new(filter))
            .inline(ctx.inline)
            .focus(true)
            .inline_title("(filter)")
            .block_title("Filter")
            .style(Style::default().fg(ctx.theme.main));

        let commands = CustomStatefulList::new(commands)
            .inline(ctx.inline)
            .block_title("Commands")
            .style(Style::default().fg(ctx.theme.main))
            .highlight_style(
                Style::default()
                    .bg(ctx.theme.selected_background)
                    .add_modifier(Modifier::BOLD),
            )
            .highlight_symbol(DEFAULT_HIGHLIGHT_SYMBOL_PREFIX);

        Ok(Self {
            commands,
            filter,
            storage,
            delegate_label: None,
            ctx,
        })
    }

    fn exit_or_label_replace(&mut self, output: ProcessOutput) -> Result<Option<ProcessOutput>> {
        if let Some(cmd) = &output.output {
            if let Some(labeled_cmd) = cmd.as_labeled_command() {
                let w = LabelProcess::new(self.storage, labeled_cmd, self.ctx)?;
                self.delegate_label = Some(w);
                return Ok(None);
            }
        }
        Ok(Some(output))
    }
}

impl<'s> Process for SearchProcess<'s> {
    fn min_height(&self) -> usize {
        (self.commands.len() + 1).clamp(4, 15)
    }

    fn peek(&mut self) -> Result<Option<ProcessOutput>> {
        if self.storage.is_empty()? {
            let message = indoc::indoc! { r#"
                -> There are no stored commands yet!
                    - Try to bookmark some command with 'Ctrl + B'
                    - Or execute 'intelli-shell fetch' to download a bunch of tldr's useful commands"# 
            };
            Ok(Some(ProcessOutput::message(message)))
        } else if !self.filter.inner().as_str().is_empty() && self.commands.len() == 1 {
            if let Some(command) = self.commands.current_mut() {
                command.increment_usage();
                self.storage.update_command(command)?;
                let cmd = command.cmd.clone();
                self.exit_or_label_replace(ProcessOutput::output(cmd))
            } else {
                Ok(None)
            }
        } else {
            Ok(None)
        }
    }

    fn render<B: Backend>(&mut self, frame: &mut Frame<B>, area: Rect) {
        // If there's a delegate active, forward to it
        if let Some(delegate) = &mut self.delegate_label {
            delegate.render(frame, area);
            return;
        }

        // Prepare main layout
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .margin(!self.ctx.inline as u16)
            .constraints([Constraint::Length(self.filter.min_size().height), Constraint::Min(1)])
            .split(area);

        let header = chunks[0];
        let body = chunks[1];

        // Render filter
        self.filter.render_in(frame, header, self.ctx.theme);

        // Render command list
        self.commands.render_in(frame, body, self.ctx.theme);
    }

    fn process_raw_event(&mut self, event: Event) -> Result<Option<ProcessOutput>> {
        // If there's a delegate active, forward to it
        if let Some(delegate) = &mut self.delegate_label {
            delegate.process_event(event)
        } else {
            self.process_event(event)
        }
    }
}

impl<'s> InteractiveProcess for SearchProcess<'s> {
    fn move_up(&mut self) {
        self.commands.previous()
    }

    fn move_down(&mut self) {
        self.commands.next()
    }

    fn move_left(&mut self) {
        self.filter.inner_mut().move_left()
    }

    fn move_right(&mut self) {
        self.filter.inner_mut().move_right()
    }

    fn prev(&mut self) {
        self.commands.previous()
    }

    fn next(&mut self) {
        self.commands.next()
    }

    fn insert_text(&mut self, text: String) -> Result<()> {
        self.filter.inner_mut().insert_text(text);
        self.commands
            .update_items(self.storage.find_commands(self.filter.inner().as_str())?);
        Ok(())
    }

    fn insert_char(&mut self, c: char) -> Result<()> {
        self.filter.inner_mut().insert_char(c);
        self.commands
            .update_items(self.storage.find_commands(self.filter.inner().as_str())?);
        Ok(())
    }

    fn delete_char(&mut self, backspace: bool) -> Result<()> {
        if self.filter.inner_mut().delete_char(backspace) {
            self.commands
                .update_items(self.storage.find_commands(self.filter.inner().as_str())?);
        }
        Ok(())
    }

    fn delete_current(&mut self) -> Result<()> {
        if let Some(command) = self.commands.delete_current() {
            self.storage.delete_command(command.id)?;
        }
        Ok(())
    }

    fn accept_current(&mut self) -> Result<Option<ProcessOutput>> {
        if let Some(command) = self.commands.current_mut() {
            command.increment_usage();
            self.storage.update_command(command)?;
            let cmd = command.cmd.clone();
            self.exit_or_label_replace(ProcessOutput::output(cmd))
        } else if !self.filter.inner().as_str().is_empty() {
            self.exit_or_label_replace(ProcessOutput::output(self.filter.inner().as_str()))
        } else {
            Ok(Some(ProcessOutput::empty()))
        }
    }

    fn exit(&mut self) -> Result<ProcessOutput> {
        if self.filter.inner().as_str().is_empty() {
            Ok(ProcessOutput::empty())
        } else {
            Ok(ProcessOutput::output(self.filter.inner().as_str()))
        }
    }
}