use crate::mosaic::RecentFiles;
use nightshade::prelude::serde::{Deserialize, Serialize};
use std::path::PathBuf;

fn default_recent_projects() -> RecentFiles {
    RecentFiles::new(10)
}

fn default_show_grid() -> bool {
    true
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(crate = "nightshade::prelude::serde")]
pub struct EditorSettingsData {
    #[serde(default)]
    pub theme_name: Option<String>,
    #[serde(default)]
    pub startup_project: Option<String>,
    #[serde(default = "default_recent_projects")]
    pub recent_projects: RecentFiles,
    #[serde(default = "default_show_grid")]
    pub show_grid: bool,
}

impl Default for EditorSettingsData {
    fn default() -> Self {
        Self {
            theme_name: None,
            startup_project: None,
            recent_projects: RecentFiles::new(10),
            show_grid: true,
        }
    }
}

pub fn get_project_name(path: &str) -> String {
    let path_buf = PathBuf::from(path);
    if let Ok(bytes) = nightshade::filesystem::read_file(std::path::Path::new(path))
        && let Ok(save_file) = nightshade::prelude::serde_json::from_slice::<
            nightshade::prelude::serde_json::Value,
        >(&bytes)
        && let Some(name) = save_file
            .get("project_name")
            .and_then(|name_value| name_value.as_str())
    {
        return name.to_string();
    }
    path_buf
        .file_stem()
        .and_then(|file_stem| file_stem.to_str())
        .unwrap_or("Unknown Project")
        .to_string()
}
