
use eframe::egui;
use egui::Ui;
use gemmaemu::chip8::computer::Chip8Computer;

struct EmmaEGuiState {
    pub display_video: bool,
    pub display_memory: bool,
    pub display_registers: bool
}

impl Default for EmmaEGuiState {
    fn default() -> Self {
        Self { display_video: true, 
            display_memory: true, 
            display_registers: true }
    }
}

fn controls_view(mut system: &mut Chip8Computer, state: &mut EmmaEGuiState, ui: &mut Ui) {
    if ui.button("Step").clicked() {
        system.step_system();
    }
    if ui.button("Start").clicked() {
        println!("Start");
    }
    if ui.button("Stop").clicked() {
        println!("STOP");

    }
    if ui.button("Reset").clicked() {

    }

    ui.checkbox(&mut state.display_memory, "Display Memory");
    ui.checkbox(&mut state.display_video, "Display Video");
    ui.checkbox(&mut state.display_registers, "Display Registers");

}

fn registers_view(system: &Chip8Computer, ui:& mut Ui) {
    ui.label(format!("V0-7: {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} ", 
    system.registers.peek(0x00),
    system.registers.peek(0x01),
    system.registers.peek(0x02),
    system.registers.peek(0x03),
    system.registers.peek(0x04),
    system.registers.peek(0x05),
    system.registers.peek(0x06),
    system.registers.peek(0x07)
));
ui.label(format!("V8-F: {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} ", 
    system.registers.peek(0x08),
    system.registers.peek(0x09),
    system.registers.peek(0x0A),
    system.registers.peek(0x0B),
    system.registers.peek(0x0C),
    system.registers.peek(0x0D),
    system.registers.peek(0x0E),
    system.registers.peek(0x0F)
));
ui.label(format!("PC: {:04x}\tI: {:04x}" , system.registers.peek_pc(), system.registers.peek_i()));
}
  
fn video_view(system: &Chip8Computer, ui: &mut Ui) {
    ui.label("Video goes here");
}

fn memory_view(system: &Chip8Computer, ui: &mut Ui) {
    ui.label("Memory View");
}


fn main() -> eframe::Result {
    println!("Taxation is Theft");

    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default().with_inner_size([320.0, 240.0]),
        ..Default::default()
    };

    let mut state = EmmaEGuiState::default();
    let mut computer = Chip8Computer::new();

    eframe::run_simple_native("EGUI Emma", options, move |ctx, _frame| {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.heading("Gemma");

            controls_view(&mut computer, &mut state, ui);

            if state.display_memory {
                memory_view(&computer, ui);
            }

            if state.display_video {
                video_view(&computer, ui);
            }
        
        if state.display_registers {
            registers_view(&computer, ui);
            }
        });
    })
}
