pub mod bus;
pub mod chrome;
mod events;
mod keys;
pub mod tabs;
mod view;

use crate::config::Config;
use crate::editor::Editor;
use crate::exec::run::Run;
use crate::settings::Form;
use crate::setup::Setup;
use crate::ui::images::Images;
use crate::vm::{self, Vm};
use crate::workflow::model::Workflow;
use crate::workflow::review::Review;
use crate::workspace::Workspace;
use bus::{Bus, Event};
use rune::{TextEdit, Tx, Waker};
use std::collections::HashMap;
use std::path::Path;
use std::rc::Rc;
use std::sync::mpsc::Receiver;
use tabs::Tab;

pub use keys::on_key;
pub use view::view;

pub enum JobKind {
    Generate(String),
    Check(String, Workflow),
    Assist(String),
    Task(String, usize),
}

pub struct App {
    pub cfg: Config,
    pub bus: Bus,
    rx: Receiver<Event>,
    pub images: Option<Rc<Images>>,
    pub setup: Setup,
    pub ws: Option<Workspace>,
    pub vm: Vm,
    machine: Option<vm::Machine>,
    pub tabs: Vec<Tab>,
    pub active: usize,
    pub editors: Vec<Editor>,
    pub reviews: Vec<Review>,
    pub runs: Vec<Run>,
    pub jobs: HashMap<u64, JobKind>,
    pub settings: Form,
    pub notice: Option<String>,
    tick: f64,
    scratch: TextEdit,
}

impl App {
    pub fn init() -> App {
        let (bus, rx) = Bus::new();
        let cfg = Config::load();
        let settings = Form::new(&cfg);
        App {
            setup: Setup::new(),
            cfg,
            bus,
            rx,
            images: None,
            ws: None,
            vm: Vm::Off,
            machine: None,
            tabs: vec![Tab::Welcome],
            active: 0,
            editors: vec![],
            reviews: vec![],
            runs: vec![],
            jobs: HashMap::new(),
            settings,
            notice: None,
            tick: 0.0,
            scratch: TextEdit::new(""),
        }
    }

    pub fn setup(s: &mut App, waker: Waker) {
        s.images = Some(Rc::new(Images::new(waker.clone())));
        s.bus.set_waker(waker);
        if let Some(dir) = std::env::args()
            .nth(1)
            .map(std::path::PathBuf::from)
            .filter(|d| d.is_dir())
        {
            s.open_dir(&dir);
        }
    }

    pub fn poll(s: &mut App, clock: f64, tx: &mut Tx) -> bool {
        let mut changed = s.autosave(clock, tx);
        while let Ok(ev) = s.rx.try_recv() {
            s.dispatch(ev);
            changed = true;
        }
        if s.runs.iter().any(|r| r.busy()) {
            tx.wake_after(std::time::Duration::from_secs(1));
            if clock.floor() != s.tick {
                s.tick = clock.floor();
                changed = true;
            }
        }
        changed
    }

    pub fn now(&self) -> f64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0.0, |d| d.as_secs_f64())
    }

    pub fn fail(&mut self, msg: impl Into<String>) {
        self.notice = Some(msg.into());
    }

    pub fn open_dir(&mut self, dir: &Path) {
        let Ok(dir) = dir.canonicalize() else {
            return self.fail("that directory does not exist");
        };
        self.machine = None;
        self.editors.clear();
        self.reviews.clear();
        self.runs.clear();
        self.jobs.clear();
        self.tabs.retain(|t| *t == Tab::Settings);
        self.cfg.touch_recent(&dir);
        let mut ws = Workspace::open(&dir);
        let first = ws
            .prompts
            .first()
            .cloned()
            .unwrap_or_else(|| ws.new_prompt());
        self.ws = Some(ws);
        self.boot_vm();
        self.open_prompt(&first);
    }

    pub fn boot_vm(&mut self) {
        let Some((dir, state)) = self.ws.as_ref().map(|w| (w.dir.clone(), w.state.clone())) else {
            return;
        };
        if !vm::files::is_baked() || rune::tooling::headless_run().is_some() {
            return;
        }
        self.machine = None;
        match vm::boot(&self.bus, &dir, &state) {
            Ok(m) => {
                self.machine = Some(m);
                self.vm = Vm::Booting;
            }
            Err(e) => self.vm = Vm::Failed(e.to_string()),
        }
    }

    pub fn port(&mut self) -> Option<u16> {
        let port = self.vm.port();
        if port.is_none() {
            self.fail("the agent VM is not running yet");
        }
        port
    }

    pub fn edit_of(&mut self, stem: &str) -> &mut TextEdit {
        match self.editors.iter().position(|e| e.stem == stem) {
            Some(i) => &mut self.editors[i].edit,
            None => &mut self.scratch,
        }
    }

    pub fn drop_machine(&mut self) {
        self.machine = None;
    }

    pub fn scratch(&mut self) -> &mut TextEdit {
        &mut self.scratch
    }
}
