use crate::app::App;
use crate::app::tabs::Tab;
use rune::{Key, KeyEvent, Tx};

pub fn on_key(s: &mut App, ev: &KeyEvent, tx: &mut Tx) -> bool {
    match ev.key {
        Key::Command('o') => s.pick_dir(tx),
        Key::Command('s') => {
            if let Tab::Prompt(stem) = s.tab().clone() {
                s.save_prompt(&stem);
            }
        }
        Key::Command('w') => s.close(s.active),
        Key::Command('n') if s.ws.is_some() => {
            let stem = s.ws.as_mut().map(|w| w.new_prompt()).unwrap_or_default();
            s.open_prompt(&stem);
        }
        Key::Command(',') => s.open(Tab::Settings),
        _ => return false,
    }
    true
}

impl App {
    pub fn pick_dir(&mut self, tx: &mut Tx) {
        let opts = rune::FileDialogOptions {
            title: "Open directory".into(),
            ..Default::default()
        };
        tx.open_folder(opts, |s: &mut App, result, _| match result {
            Ok(Some(dir)) => s.open_dir(&dir),
            Ok(None) => {}
            Err(e) => s.fail(e.to_string()),
        });
    }
}
