use serde::{Serialize, Deserialize};
use std::path::PathBuf;

#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    elastic_url: String,
    credentials: Option<Credentials>
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Credentials {
    username: String,
    password: String
}

/// `Config` implements `Default`
impl ::std::default::Default for Config {
    fn default() -> Self { Self { 
        elastic_url: "http://elastic-url.com".into(),
        credentials: Some(Credentials{
            username: "default_user".into(),
            password: "default_password".into()
        } )
    } }
}

/// Loads elastic config from path
/// 
/// A new configuration file is created if none already exists
/// 
/// ```rust, no_run
/// let config = config::read_config("path-to.yaml")
/// let elastic_url = config.elastic.url
/// ```
pub fn read_config(p: &Option<PathBuf>) -> Config {
    let config_path: PathBuf = match p {
        Some(d) => d.to_owned(),
        None => create_path_in_config_dir("config.toml")
    };

    return confy::load_path(&config_path).expect("No config found");
}

pub fn create_path_in_config_dir(file_name: &str) -> PathBuf {
    let home_dir = dirs::home_dir().map(|p| p.into_os_string().into_string().unwrap());
    

    match home_dir {
        Some(d) => {
            let c: PathBuf = [&d, ".elastic4r", file_name].iter().collect();
            c
        }
        None => {
            PathBuf::from(file_name)
        }
    }
}
