/// Application.
pub mod app;

/// Terminal events handler.
pub mod event;

/// Widget renderer.
pub mod ui;

/// Terminal user interface.
pub mod tui;

/// Event handler.
pub mod handler;

/// Data model.
pub mod car;

extern crate ratatui;
use std::io;

use app::{App, AppResult};
use dittolive_ditto::prelude::AppId;
use event::{Event, EventHandler};
use handler::handle_key_events;
use ratatui::prelude::*;
use tui::Tui;

fn main() -> AppResult<()> {
    // Create an application.
    let app_id = AppId::from_env("DITTO_APP_ID").unwrap();
    let shared_token = std::env::var("DITTO_SHARED_TOKEN").unwrap();
    let mut app = App::new(app_id, shared_token);
    app.start_pooling();
    // Initialize the terminal user interface.
    let backend = CrosstermBackend::new(io::stderr());
    let terminal = Terminal::new(backend)?;
    let events = EventHandler::new(250);
    let mut tui = Tui::new(terminal, events);
    tui.init()?;

    // Start the main loop.
    while app.running {
        // Render the user interface.
        tui.draw(&mut app)?;
        // Handle events.
        match tui.events.next()? {
            Event::Tick => app.tick(),
            Event::Key(key_event) => handle_key_events(key_event, &mut app)?,
            Event::Mouse(_) => {}
            Event::Resize(_, _) => {}
        }
    }

    // Exit the user interface.
    tui.exit()?;
    Ok(())
}
