use std::{
    sync::{Arc, Mutex},
    thread,
};

use dsa_rs::emulator::{
    system::{emulator::run_emulator, memory::MainStore, processor::Processor},
    ui::{
        control_unit::ControlPanel, interface::EmulatorUI, memory_inspector::MemoryInspector,
        stack_inspector::StackInspector,
    },
};

fn main() -> Result<(), eframe::Error> {
    // Initialize Channels
    let (cmd_sender, cmd_receiver) = std::sync::mpsc::channel();
    let (state_sender, state_receiver) = std::sync::mpsc::channel();

    let mainstore = MainStore::new();
    let processor = Processor::new(Box::new(mainstore), vec![]);

    thread::spawn(move || {
        run_emulator(&cmd_receiver, &state_sender, processor);
    });

    // Create UI
    let mut ui = EmulatorUI::new(cmd_sender.clone(), state_receiver);

    // Create UI modules
    let control_unit = ControlPanel::new(cmd_sender.clone());
    ui.add_component(Box::new(control_unit));

    let mem_inspector = MemoryInspector::new(cmd_sender.clone());
    ui.add_component(Box::new(mem_inspector));

    let stack_inspector = StackInspector::new();
    ui.add_component(Box::new(stack_inspector));

    // Run UI
    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))
        }),
    )
}
