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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use nu_data::utils::{report as build_report, Model};
use nu_errors::ShellError;
use nu_plugin::Plugin;
use nu_protocol::{CallInfo, ColumnPath, Primitive, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::{Tagged, TaggedItem};
use nu_value_ext::ValueExt;

use crate::bar::Bar;

use std::{
    error::Error,
    io::{stdout, Write},
    sync::mpsc,
    thread,
    time::{Duration, Instant},
};

use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event as CEvent, KeyCode},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};

use tui::{backend::CrosstermBackend, Terminal};

enum Event<I> {
    Input(I),
    Tick,
}

pub enum Columns {
    One(Tagged<String>),
    Two(Tagged<String>, Tagged<String>),
    None,
}

#[allow(clippy::type_complexity)]
pub struct SubCommand {
    pub reduction: nu_data::utils::Reduction,
    pub columns: Columns,
    pub eval: Option<Box<dyn Fn(usize, &Value) -> Result<Value, ShellError> + Send>>,
    pub format: Option<String>,
}

impl Default for SubCommand {
    fn default() -> Self {
        Self::new()
    }
}

impl SubCommand {
    pub fn new() -> SubCommand {
        SubCommand {
            reduction: nu_data::utils::Reduction::Count,
            columns: Columns::None,
            eval: None,
            format: None,
        }
    }
}

fn display(model: &Model) -> Result<(), Box<dyn Error>> {
    let mut app = Bar::from_model(&model)?;

    enable_raw_mode()?;

    let mut stdout = stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;

    let backend = CrosstermBackend::new(stdout);

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

    let (tx, rx) = mpsc::channel();

    let tick_rate = Duration::from_millis(250);
    thread::spawn(move || {
        let mut last_tick = Instant::now();
        loop {
            if event::poll(tick_rate - last_tick.elapsed()).is_ok() {
                if let Ok(CEvent::Key(key)) = event::read() {
                    let _ = tx.send(Event::Input(key));
                }
            }
            if last_tick.elapsed() >= tick_rate {
                let _ = tx.send(Event::Tick);
                last_tick = Instant::now();
            }
        }
    });

    terminal.clear()?;

    loop {
        app.draw(&mut terminal)?;

        match rx.recv()? {
            Event::Input(event) => match event.code {
                KeyCode::Left => app.on_left(),
                KeyCode::Right => app.on_right(),
                KeyCode::Char('q') => {
                    disable_raw_mode()?;
                    execute!(
                        terminal.backend_mut(),
                        LeaveAlternateScreen,
                        DisableMouseCapture
                    )?;
                    terminal.show_cursor()?;
                    break;
                }
                _ => {
                    disable_raw_mode()?;
                    execute!(
                        terminal.backend_mut(),
                        LeaveAlternateScreen,
                        DisableMouseCapture
                    )?;
                    terminal.show_cursor()?;
                    break;
                }
            },
            Event::Tick => {}
        }
    }

    Ok(())
}

impl Plugin for SubCommand {
    fn config(&mut self) -> Result<Signature, ShellError> {
        Ok(Signature::build("chart bar")
            .desc("Bar charts")
            .switch("acc", "accumulate values", Some('a'))
            .optional(
                "columns",
                SyntaxShape::Any,
                "the columns to chart [x-axis y-axis]",
            )
            .named(
                "use",
                SyntaxShape::ColumnPath,
                "column to use for evaluation",
                Some('u'),
            )
            .named(
                "format",
                SyntaxShape::String,
                "Specify date and time formatting",
                Some('f'),
            ))
    }

    fn sink(&mut self, call_info: CallInfo, input: Vec<Value>) {
        if let Some(Value {
            value: UntaggedValue::Primitive(Primitive::Boolean(true)),
            ..
        }) = call_info.args.get("acc")
        {
            self.reduction = nu_data::utils::Reduction::Accumulate;
        }

        let _ = self.run(call_info, input);
    }
}

impl SubCommand {
    fn run(&mut self, call_info: CallInfo, input: Vec<Value>) -> Result<(), ShellError> {
        let args = call_info.args;
        let name = call_info.name_tag;

        self.eval = if let Some(path) = args.get("use") {
            Some(evaluator(path.as_column_path()?.item))
        } else {
            None
        };

        self.format = if let Some(fmt) = args.get("format") {
            Some(fmt.as_string()?)
        } else {
            None
        };

        for arg in args.positional_iter() {
            match arg {
                Value {
                    value: UntaggedValue::Primitive(Primitive::String(column)),
                    tag,
                } => {
                    let column = column.clone();
                    self.columns = Columns::One(column.tagged(tag));
                }
                Value {
                    value: UntaggedValue::Table(arguments),
                    tag,
                } => {
                    if arguments.len() > 1 {
                        let col1 = arguments
                            .get(0)
                            .ok_or_else(|| {
                                ShellError::labeled_error(
                                    "expected file and replace strings eg) [find replace]",
                                    "missing find-replace values",
                                    tag,
                                )
                            })?
                            .as_string()?
                            .tagged(tag);

                        let col2 = arguments
                            .get(1)
                            .ok_or_else(|| {
                                ShellError::labeled_error(
                                    "expected file and replace strings eg) [find replace]",
                                    "missing find-replace values",
                                    tag,
                                )
                            })?
                            .as_string()?
                            .tagged(tag);

                        self.columns = Columns::Two(col1, col2);
                    } else {
                        let col1 = arguments
                            .get(0)
                            .ok_or_else(|| {
                                ShellError::labeled_error(
                                    "expected file and replace strings eg) [find replace]",
                                    "missing find-replace values",
                                    tag,
                                )
                            })?
                            .as_string()?
                            .tagged(tag);

                        self.columns = Columns::One(col1);
                    }
                }
                _ => {}
            }
        }

        let data = UntaggedValue::table(&input).into_value(&name);

        match &self.columns {
            Columns::Two(col1, col2) => {
                let key = col1.clone();
                let fmt = self.format.clone();

                let grouper = Box::new(move |_: usize, row: &Value| {
                    let key = key.clone();
                    let fmt = fmt.clone();

                    match row.get_data_by_key(key.borrow_spanned()) {
                        Some(key) => {
                            if let Some(fmt) = fmt {
                                let callback = nu_data::utils::helpers::date_formatter(fmt);
                                callback(&key, "nothing".to_string())
                            } else {
                                nu_value_ext::as_string(&key)
                            }
                        }
                        None => Err(ShellError::labeled_error(
                            "unknown column",
                            "unknown column",
                            key.tag(),
                        )),
                    }
                });

                let key = col2.clone();
                let splitter = Box::new(move |_: usize, row: &Value| {
                    let key = key.clone();

                    match row.get_data_by_key(key.borrow_spanned()) {
                        Some(key) => nu_value_ext::as_string(&key),
                        None => Err(ShellError::labeled_error(
                            "unknown column",
                            "unknown column",
                            key.tag(),
                        )),
                    }
                });

                let formatter = if self.format.is_some() {
                    let default = String::from("%b-%Y");

                    let string_fmt = self.format.as_ref().unwrap_or(&default);

                    Some(nu_data::utils::helpers::date_formatter(
                        string_fmt.to_string(),
                    ))
                } else {
                    None
                };

                let options = nu_data::utils::Operation {
                    grouper: Some(grouper),
                    splitter: Some(splitter),
                    format: &formatter,
                    eval: &self.eval,
                    reduction: &self.reduction,
                };

                let _ = display(&build_report(&data, options, &name)?);
            }
            Columns::One(col) => {
                let key = col.clone();
                let fmt = self.format.clone();

                let grouper = Box::new(move |_: usize, row: &Value| {
                    let key = key.clone();
                    let fmt = fmt.clone();

                    match row.get_data_by_key(key.borrow_spanned()) {
                        Some(key) => {
                            if let Some(fmt) = fmt {
                                let callback = nu_data::utils::helpers::date_formatter(fmt);
                                callback(&key, "nothing".to_string())
                            } else {
                                nu_value_ext::as_string(&key)
                            }
                        }
                        None => Err(ShellError::labeled_error(
                            "unknown column",
                            "unknown column",
                            key.tag(),
                        )),
                    }
                });

                let formatter = if self.format.is_some() {
                    let default = String::from("%b-%Y");

                    let string_fmt = self.format.as_ref().unwrap_or(&default);

                    Some(nu_data::utils::helpers::date_formatter(
                        string_fmt.to_string(),
                    ))
                } else {
                    None
                };

                let options = nu_data::utils::Operation {
                    grouper: Some(grouper),
                    splitter: None,
                    format: &formatter,
                    eval: &self.eval,
                    reduction: &self.reduction,
                };

                let _ = display(&build_report(&data, options, &name)?);
            }
            _ => {}
        }

        Ok(())
    }
}

pub fn evaluator(by: ColumnPath) -> Box<dyn Fn(usize, &Value) -> Result<Value, ShellError> + Send> {
    Box::new(move |_: usize, value: &Value| {
        let path = by.clone();

        let eval = nu_value_ext::get_data_by_column_path(value, &path, move |_, _, error| error);

        match eval {
            Ok(with_value) => Ok(with_value),
            Err(reason) => Err(reason),
        }
    })
}