use std::io::{Read, Write};
use std::fs::{self, File};
use std::path::PathBuf;
use std::env::home_dir;

use error::*;

use serde_json;

lazy_static! {
    pub static ref CONFIG: Config = read_config().expect("Failed to read configuration.");
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    pub host: String,
    pub key: String
}

fn config_path() -> PathBuf {
    home_dir()
        .expect("Failed to locate home directory.")
        .join(".config")
        .join("ComfyPush")
        .join("client-config.json")
}

pub fn read_config() -> ComfyResult<Config> {
    let mut body = String::new();
    let mut file = File::open(config_path())?;
    file.read_to_string(&mut body)?;
    serde_json::from_str(&body)
        .map_err(ComfyError::from)
}

pub fn write_config(host: &str, key: &str) -> ComfyResult<Config> 
{
    let path = config_path();
    fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics
    let mut file = File::open(path)?;
    let body = serde_json::to_string(&Config {
        host: host.to_string(),
        key: key.to_string()
    })?;
    serde_json::from_str(&body)
        .map_err(ComfyError::from)
}