use std::sync::{Arc, atomic::Ordering};

use super::Component;
use crate::{MemoryBank, SharedState};

use common::prelude::Register;

pub struct Controller {
    state: Arc<SharedState>,
    mem: MemoryBank,
    visible: bool,
}

impl Controller {
    pub fn new(state: Arc<SharedState>, mem: MemoryBank) -> Self {
        Self {
            state,
            mem,
            visible: false,
        }
    }
}

impl Component for Controller {
    fn title(&self) -> &str {
        "Control Panel"
    }

    fn visible(&mut self) -> &mut bool {
        &mut self.visible
    }

    fn ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
        let state = self.state.proc.load();

        let paused = self.state.paused.load(Ordering::Relaxed);

        ui.horizontal(|ui| {
            // Pause / Run
            if ui
                .button(match paused {
                    false => "Pause",
                    true => "Resume",
                })
                .clicked()
            {
                self.state.paused.store(!paused, Ordering::Relaxed);
            }

            // Step
            // if ui.button("Step").clicked() {
            //     state
            //         .cmd_sender
            //         .send(Command::Step(self.step_amount))
            //         .unwrap_or_else(|_| {
            //             state.error_log.push("Failed to send command".to_string());
            //         });
            // }

            // Resets the emulator and all attached devices
            if ui.button("Reset All").clicked() {
                self.state.reseting.store(true, Ordering::Relaxed);
                self.mem.clear();
                self.state.reseting.store(false, Ordering::Relaxed);
            }

            ui.separator();

            // if ui
            //     .text_edit_singleline(&mut self.step_amount_input)
            //     .changed()
            // {
            //     self.step_amount = if let Ok(amount) = self.step_amount_input.parse() {
            //         amount
            //     } else {
            //         state
            //             .error_log
            //             .push("Unable to parse step amount".to_string());
            //         1
            //     }
            // }

            // Status info
            ui.label(format!(
                "Status: {}",
                match (state.halted, paused) {
                    (true, false) => "Halted",
                    (_, false) => "Running",
                    (_, true) => "Paused",
                }
            ));

            let pcx = state.registers[Register::Pcx as usize];
            let clock = state.clock;
            let time = state.time.as_micros();
            let mips = state.clock as u128 / time;

            ui.label(format!("Clock: {clock}"));
            ui.label(format!("Pcx: 0x{pcx:08X}"));
            ui.label(format!("Elapsed: {}micros", time));
            ui.label(format!("Freq: {}MHz", mips));
        });
    }
}
