use egui::{TextEdit, vec2};

use crate::{PROJECT_FOLDER, util};

#[derive(Debug, Clone)]
pub struct Asset {
    pub new_name: String,
    pub name: String,
    pub saved: bool,
}

impl Asset {
    pub fn open(name: String) -> Self {
        Self {
            new_name: name.clone(),
            name,
            saved: true,
        }
    }

    pub fn save(&mut self) {
        let old_path = Self::path(&self.name);
        let new_path = Self::path(&self.new_name);

        println!("old_path: {old_path:?}");
        println!("new_path: {new_path:?}");

        // move from src dir to name path
        if let Err(err) = std::fs::rename(&old_path, &new_path) {
            match err.kind() {
                std::io::ErrorKind::NotFound => {
                    let dir = new_path.parent().unwrap();
                    if !dir.exists() {
                        std::fs::create_dir_all(dir).unwrap();
                    }
                    std::fs::rename(&old_path, &new_path).unwrap();
                }
                _ => panic!("Failed to rename file: {err}"),
            }
        }
        self.saved = true;
        self.name = self.new_name.clone();
    }

    pub fn path(name: &str) -> std::path::PathBuf {
        PROJECT_FOLDER.join("assets").join(name)
    }

    pub fn ui(&mut self, ui: &mut egui::Ui) {
        ui.vertical(|ui| {
            util::saved_status(ui, self.saved, &self.name, &self.new_name);

            if ui.input(|i| i.key_pressed(egui::Key::S) && i.modifiers.ctrl)
                || ui.button("Save").clicked()
            {
                self.save();
            }

            ui.separator();

            ui.horizontal(|ui| {
                ui.strong("Filename:");
                if TextEdit::singleline(&mut self.new_name)
                    .desired_width(f32::INFINITY)
                    .frame(false)
                    .show(ui)
                    .response
                    .changed()
                {
                    self.saved = false;
                }
            });

            ui.separator();

            if let Ok(bytes) = std::fs::read(Self::path(&self.name)) {
                let image_source = egui::ImageSource::Bytes {
                    uri: std::borrow::Cow::Owned(self.name.clone()),
                    bytes: bytes.into(),
                };
                ui.add(
                    egui::Image::new(image_source)
                        .max_size(vec2(ui.available_width(), f32::INFINITY)),
                );
            }
        });
    }
}
