use std::io::Read;

use chrono::NaiveDate;
use egui_extras::DatePickerButton;
use serde::{Deserialize, Serialize};

use crate::PROJECT_FOLDER;

#[derive(Serialize, Deserialize)]
pub struct ProjectContext {
    date: NaiveDate,
    project_name: String,
    project_author: String,
    project_description: String,
}

impl ProjectContext {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn load() -> Self {
        let path = PROJECT_FOLDER.join("context.json");
        if let Ok(mut file) = std::fs::File::open(path) {
            let mut contents = String::new();
            file.read_to_string(&mut contents).unwrap();
            if let Ok(proj) = serde_json::from_str(&contents) {
                return proj;
            }
        }
        Self::default()
    }

    pub fn save(&self) {
        let path = PROJECT_FOLDER.join("context.json");
        let content = serde_json::to_string_pretty(self).unwrap();
        std::fs::write(path, content).unwrap();
    }

    pub fn ui(&mut self, ui: &mut egui::Ui) {
        // table
        egui::Grid::new("context_editor")
            .striped(true)
            .num_columns(2)
            .show(ui, |ui| {
                ui.label("Project Name");
                ui.text_edit_singleline(&mut self.project_name);

                ui.end_row();

                ui.label("Project Author");
                ui.text_edit_singleline(&mut self.project_author);

                ui.end_row();

                ui.label("Project Description");
                ui.text_edit_singleline(&mut self.project_description);

                ui.end_row();

                ui.label("Date");
                ui.add(DatePickerButton::new(&mut self.date));

                ui.end_row();
            });
    }
}

impl Default for ProjectContext {
    fn default() -> Self {
        Self {
            date: chrono::Local::now().naive_local().into(),
            project_name: "New Project".to_string(),
            project_author: "Your Name".to_string(),
            project_description: "Description of your project".to_string(),
        }
    }
}
