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
use super::{
    data::build_sorted_filtered_query, data::build_sorted_query, data::Db, data::CAST_COLUMN,
    data::COUNTRY_COLUMN, data::GENRE_COLUMN, data::LANGUAGE_COLUMN, data::PLOT_COLUMN,
    data::TITLE_COLUMN, render::maybe_render_item_details, render::render_admin,
    render::render_log, render::render_rows_summary, render::App, render::Log,
};
use crossterm::{
    event::{poll, read, Event, KeyCode, KeyEvent, KeyModifiers},
    terminal::disable_raw_mode,
    terminal::enable_raw_mode,
};
use std::{error::Error, io::stdout, process, time::Duration};
use tui::{
    backend::Backend, backend::CrosstermBackend, layout::Constraint, layout::Direction,
    layout::Layout, layout::Rect, Frame, Terminal,
};

const PAGE_MARGIN_HEIGHT: i32 = 3;

fn render_summary_and_admin<B>(f: &mut Frame<B>, app: &mut App, container: Rect) -> (Rect, Rect)
where
    B: Backend,
{
    let items = render_rows_summary(&app.items.items);

    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(40), Constraint::Percentage(60)].as_ref())
        .split(container);

    let admin_container = chunks[0];
    let summary_container = chunks[1];

    render_admin(f, app, admin_container);
    let list_state = &mut app.items.state;
    f.render_stateful_widget(items, summary_container, list_state);

    (admin_container, summary_container)
}

fn exec_query(app: &mut App, db: &Db) -> Result<(), Box<dyn Error>> {
    let rows = if app.has_any_query() {
        let q = build_sorted_filtered_query(
            vec![
                (GENRE_COLUMN, &app.genre_query).into(),
                (TITLE_COLUMN, &app.title_query).into(),
                (CAST_COLUMN, &app.cast_query).into(),
                (COUNTRY_COLUMN, &app.country_query).into(),
                (LANGUAGE_COLUMN, &app.language_query).into(),
                (PLOT_COLUMN, &app.plot_query).into(),
            ],
            &app.item_type,
        );
        app.logs.push(Log::Debug(q.to_string()));

        match db.get_no_params_query_result(&q) {
            Ok(rows) => Ok(rows),
            Err(err) => {
                app.logs.push(Log::Error(err.to_string()));
                db.get_synced_rows_sorted()
            }
        }
    } else {
        let q = build_sorted_query(&app.item_type);
        app.logs.push(Log::Debug(q.to_string()));

        match db.get_no_params_query_result(&q) {
            Ok(rows) => Ok(rows),
            Err(err) => {
                app.logs.push(Log::Error(err.to_string()));
                db.get_synced_rows_sorted()
            }
        }
    }?;

    app.items.unselect();
    app.items.items = rows;
    if !app.items.items.is_empty() {
        app.items.next()
    }
    Ok(())
}

pub fn tui(db: Db) -> Result<(), Box<dyn Error>> {
    let _show_log: bool = false;
    #[cfg(feature = "log")]
    let _show_log: bool = true;

    let all_rows = db.get_synced_rows_sorted()?;
    if all_rows.len() == 0 {
        eprintln!(
            "It looks like you have no rated items in your database yet.
Make sure sync them by running 'nf-rated sync' first!"
        );
        process::exit(1);
    }

    enable_raw_mode()?;

    let stdout = stdout();
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let mut app = App::new(all_rows);
    app.items.state.select(Some(0));

    let mut current_summary_size: Rect = Default::default();
    let constraints = if _show_log {
        vec![
            Constraint::Percentage(60),
            Constraint::Percentage(25),
            Constraint::Percentage(15),
        ]
    } else {
        vec![Constraint::Percentage(70), Constraint::Percentage(30)]
    };

    terminal.clear()?;
    loop {
        terminal.draw(|mut f| {
            let main_container = Layout::default()
                .direction(Direction::Vertical)
                .constraints(constraints.as_ref())
                .split(f.size());

            let (summary_and_config_container, item_details_container, log_container) = if _show_log
            {
                (main_container[0], main_container[1], main_container[2])
            } else {
                (main_container[0], main_container[1], main_container[1])
            };

            let (_, summary_container) =
                render_summary_and_admin(&mut f, &mut app, summary_and_config_container);
            current_summary_size = summary_container;

            let selected_idx = app.items.state.selected();
            let item_details = if selected_idx.is_none() {
                maybe_render_item_details(None)
            } else {
                maybe_render_item_details(app.items.items.get(selected_idx.unwrap()))
            };
            f.render_widget(item_details, item_details_container);

            if _show_log {
                f.render_widget(render_log(&app.logs), log_container)
            };
        })?;

        if poll(Duration::from_millis(200))? {
            let event = read()?;
            match event {
                //
                // Quit
                //
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::NONE,
                    code: KeyCode::Esc,
                })
                | Event::Key(KeyEvent {
                    modifiers: KeyModifiers::CONTROL,
                    code: KeyCode::Char('c'),
                }) => {
                    break;
                }

                //
                // Navigate list by item
                //
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::CONTROL,
                    code: KeyCode::Char('n'),
                })
                | Event::Key(KeyEvent {
                    modifiers: KeyModifiers::NONE,
                    code: KeyCode::Down,
                }) => {
                    app.items.next();
                }
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::CONTROL,
                    code: KeyCode::Char('p'),
                })
                | Event::Key(KeyEvent {
                    modifiers: KeyModifiers::NONE,
                    code: KeyCode::Up,
                }) => {
                    app.items.previous();
                }

                //
                // Navigate list by page
                //
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::CONTROL,
                    code: KeyCode::Char('d'),
                }) => {
                    app.items.next_page(
                        (current_summary_size.height as i32 - PAGE_MARGIN_HEIGHT).max(1),
                    );
                }
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::CONTROL,
                    code: KeyCode::Char('u'),
                }) => {
                    app.items.previous_page(
                        (current_summary_size.height as i32 - PAGE_MARGIN_HEIGHT).max(1),
                    );
                }

                //
                // Configure item type
                //
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::CONTROL,
                    code: KeyCode::Char('o'),
                }) => {
                    app.next_item_type();
                    exec_query(&mut app, &db)?;
                }

                //
                // Navigate filter inputs
                //
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::NONE,
                    code: KeyCode::Tab,
                }) => {
                    app.next_query_field();
                }
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::NONE,
                    code: KeyCode::BackTab,
                }) => {
                    app.logs.push(Log::Info("left".to_string()));
                    app.prev_query_field();
                }

                //
                // Enter query
                //
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::NONE,
                    code: KeyCode::Backspace,
                }) => {
                    app.pop_off_query();
                    exec_query(&mut app, &db)?;
                }
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::NONE,
                    code: KeyCode::Char(c),
                })
                | Event::Key(KeyEvent {
                    modifiers: KeyModifiers::SHIFT,
                    code: KeyCode::Char(c),
                }) => {
                    app.push_onto_query(c);
                    exec_query(&mut app, &db)?;
                }
                Event::Key(KeyEvent {
                    modifiers: KeyModifiers::CONTROL,
                    code: KeyCode::Char('e'),
                }) => {
                    app.logs.push(Log::Info("clearing all queries".to_string()));
                    app.clear_all_queries();
                    exec_query(&mut app, &db)?;
                }
                _ => {}
            }
        }
    }

    terminal.clear()?;
    terminal.set_cursor(0, 0)?;

    disable_raw_mode()?;
    Ok(())
}