use anyhow::Result;
use kordophone_db::settings::Settings as DbSettings;

pub mod keys {
    pub static SERVER_URL: &str = "ServerURL";
    pub static USERNAME: &str = "Username";
    pub static TOKEN: &str = "Token";
}

#[derive(Debug, Default)]
pub struct Settings {
    pub server_url: Option<String>,
    pub username: Option<String>,
    pub token: Option<String>,
}

impl Settings {
    pub fn from_db(db_settings: &mut DbSettings) -> Result<Self> {
        let server_url = db_settings.get(keys::SERVER_URL)?;
        let username = db_settings.get(keys::USERNAME)?;
        let token = db_settings.get(keys::TOKEN)?;

        // Create the settings struct with the results
        let settings = Self {
            server_url,
            username,
            token,
        };

        // Load bearing
        log::debug!("Loaded settings: {:?}", settings);

        Ok(settings)
    }

    pub fn save(&self, db_settings: &mut DbSettings) -> Result<()> {
        if let Some(server_url) = &self.server_url {
            db_settings.put(keys::SERVER_URL, &server_url)?;
        }
        if let Some(username) = &self.username {
            db_settings.put(keys::USERNAME, &username)?;
        }
        if let Some(token) = &self.token {
            db_settings.put(keys::TOKEN, &token)?;
        }
        Ok(())
    }
}
