use crossterm::{
    event::{DisableMouseCapture, EnableMouseCapture},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use kanal::{Receiver, Sender};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::{error::Error, io};

mod app;
mod data;
mod input_form;
mod midi;
mod ui;
use app::App;
use midi::{MidiCommand, MidiSender};
use ui::run_app;

fn main() -> Result<(), Box<dyn Error>> {
    // Create JACK client
    let (client, status) =
        jack::Client::new("FCB1010_Mapper", jack::ClientOptions::NO_START_SERVER)?;
    if !status.is_empty() {
        eprintln!("JACK client status: {:?}", status);
    }

    // Create command channel
    let (command_sender, command_receiver): (Sender<MidiCommand>, Receiver<MidiCommand>) =
        kanal::bounded(32);

    // Create MIDI sender
    let midi_sender = MidiSender::new(&client, command_receiver)?;

    // Activate client
    let _active_client = client.activate_async((), midi_sender)?;

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Create app and run
    let app = App::new(command_sender);
    let res = run_app(&mut terminal, app);

    // Restore terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    if let Err(err) = res {
        println!("{:?}", err);
    }

    Ok(())
}
