use std::env;
use std::path::Path;
use std::sync::Arc;

use dsa_rs::emulator::{config::Config, misc::rpc::get_rpc_client_or_none};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    if env::args().any(|arg| arg == "--cli") {
        dsa_rs::emulator::cli::run_cli()?;
        std::process::exit(0);
    }

    // Initialize channels and read in configuration.
    let (cmd_sender, cmd_receiver) = std::sync::mpsc::channel();
    let (state_sender, state_reciever) = std::sync::mpsc::channel();
    let config = Config::load(Path::new(".dsa.emulator.toml"))?;

    // Setup RPC if enabled.
    let (rpc_sender, rpc_reciever) = std::sync::mpsc::channel();

    let rpc_client =
        get_rpc_client_or_none(&config, rpc_sender, rpc_reciever)?.map(Arc::new);

    dsa_rs::setup_emulator(cmd_receiver, state_sender, rpc_client);

    let ui = dsa_rs::setup_ui(cmd_sender, state_reciever);

    // Run UI.
    #[allow(unused_variables)]
    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default().with_inner_size([800.0, 600.0]),
        ..Default::default()
    };

    eframe::run_native(
        "DSA Simulator (Damn Simple Architecture 🔥)",
        options,
        Box::new(move |cc| {
            cc.egui_ctx.set_visuals(egui::Visuals::default());
            Ok(Box::new(ui))
        }),
    )?;

    Ok(())
}
