use std::fs::read_dir;
use std::ops::Index;
use std::path::{Display, PathBuf};
use std::thread;
use std::time::Duration;
use egui::{Align, Color32, ComboBox, Direction, Pos2, Response, TextBuffer};
use egui::Rect;
use egui::Vec2;
use egui::Ui;
use egui::WidgetType::SelectableLabel;
use crate::Chip8Computer;

const CELL_WIDTH: f32 = 5.0;
const CELL_HEIGHT: f32 = 5.0;

pub struct EGuiFileList {}
impl EGuiFileList {
    pub fn display_path(root: PathBuf, selected_filename: &mut String, ui: &mut Ui) {
        let mut working_filename = selected_filename.clone();
        ui.with_layout(egui::Layout::left_to_right(egui::Align::TOP), |ui| {
           //  ui.label(format!("Displaying {}", root.to_str().unwrap_or("Unable to Load Path")));
            ComboBox::from_label("Select ROM")
                .selected_text(selected_filename.clone())
                .show_ui(ui, |ui| {

                    let mut sorted_options = vec![];
                    for option in read_dir(root.as_path()).unwrap() {
                        let to_push = option.unwrap().file_name().into_string().unwrap_or( String::new());
                        sorted_options.push(to_push);
                    }

                    sorted_options.sort();
                    for item in sorted_options {
                    // Add each option to the ComboBox
                      if  ui.selectable_label(selected_filename.eq(&item.as_str()), item.clone()).clicked()
                        {
                            *selected_filename = item;
                        }
                    }
                });
            // Display the selected option
        });
    }
}

pub struct GemmaEguiSupport {}

impl GemmaEguiSupport {
    pub fn controls_view(mut system: &mut Chip8Computer, ui: &mut Ui) {
         ui.with_layout(egui::Layout::left_to_right(egui::Align::TOP), |ui| {
             if ui.button("Start").clicked() {
                 println!("Start");
          //       state.is_running = true;
             }
             if ui.button("Step").clicked() {
                 system.step_system();
             }

             if ui.button("Stop").clicked() {
                 println!("STOP");
            //     state.is_running = false;
             }
             if ui.button("Reset").clicked() {
                 system.reset();
              //   state.is_running = false;
             }
         });

     //       if ui.button(format!("Load {}", state.selected_rom_filename)).clicked() {
                // load the bin...
       //         let read_bin = std::fs::read(PathBuf::from(format!("resources/roms/{}", state.selected_rom_filename))).unwrap();
                // ...then feed the system.
       //         system.load_bytes_to_memory(0x200, &read_bin);
       //         println!("Loaded {}", state.selected_rom_filename);
       //     }
       //      EGuiFileList::display_path(PathBuf::from("resources/roms"), &mut state.selected_rom_filename, ui);



        ui.with_layout(egui::Layout::left_to_right(Align::TOP), |ui| {
        //    ui.checkbox(&mut state.display_memory, "Display Memory");
        //    ui.checkbox(&mut state.display_video, "Display Video");
         //   ui.checkbox(&mut state.display_registers, "Display Registers");
        });
    }

    pub 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()));
    }

    pub fn video_view(system: &Chip8Computer, ui: &mut Ui) {
        let (_resp, painter) = ui.allocate_painter(Vec2::new(350.0, 165.0), egui::Sense::hover());
        for current_row in 0..32 {
            for current_col in 0..64 {
                let data_offset = current_row * 64 + current_col;
                let x_offset = current_col as f32 * CELL_WIDTH;
                let y_offset = current_row as f32 * CELL_HEIGHT;
                let origin = Pos2::new(x_offset, y_offset);
                let colour = if system.video_memory.peek(data_offset) {
                    Color32::RED
                } else {
                    Color32::WHITE
                };
                let rect = Rect::from_min_size(origin, Vec2::new(CELL_WIDTH, CELL_HEIGHT));
                painter.rect_filled(rect, 0.0, colour);
                // println!("Cell {current_col}x{current_row} at {}x{} -> {}",
                //          origin.x, origin.y,
                //          system.video_memory.peek(data_offset));
            }
        }
    //    thread::sleep(Duration::from_secs(1));
    }

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

        for i in (0..=0x200).step_by(16) {
            ui.with_layout(egui::Layout::left_to_right(egui::Align::TOP), |ui| {
                for y in 0..16 {
                    ui.label(format!("{:02x}", system.memory.peek((i + y) as u16)).as_str());
                }
            });
        }
        ui.label("Should have **something** to adjust the 'memory window'");
    }
}
