use std::{env, path::PathBuf};

const NAME: &str = env!("CARGO_PKG_NAME");

pub fn home() -> PathBuf {
    if let Ok(home) = env::var("HOME") {
        PathBuf::from(home)
    } else {
        PathBuf::new()
    }
}

/// Choosing directories according to https://specifications.freedesktop.org/basedir/latest/#variables
pub mod xdg {
    use super::*;

    pub const DATA_HOME: &str = "XDG_DATA_HOME";

    /// $XDG_DATA_HOME defines the base directory relative to which user-specific data files should be stored.
    /// If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used.
    pub fn data_home() -> PathBuf {
        if let Some(dir) = env::var_os(DATA_HOME) {
            PathBuf::from(dir)
        } else {
            home().join(".local/share")
        }
    }

    pub const CONFIG_HOME: &str = "XDG_CONFIG_HOME";

    /// $XDG_CONFIG_HOME defines the base directory relative to which user-specific configuration files should be stored.
    /// If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used.
    pub fn config_home() -> PathBuf {
        if let Some(dir) = env::var_os(CONFIG_HOME) {
            PathBuf::from(dir)
        } else {
            home().join(".config")
        }
    }

    pub const STATE_HOME: &str = "XDG_STATE_HOME";

    /// $XDG_STATE_HOME defines the base directory relative to which user-specific state files should be stored.
    /// If $XDG_STATE_HOME is either not set or empty, a default equal to $HOME/.local/state should be used.
    pub fn state_home() -> PathBuf {
        if let Some(dir) = env::var_os(STATE_HOME) {
            PathBuf::from(dir)
        } else {
            home().join(".local/state")
        }
    }
}

pub fn data_dir() -> PathBuf {
    xdg::data_home().join(NAME)
}

pub fn config_dir() -> PathBuf {
    xdg::config_home().join(NAME)
}

pub fn state_dir() -> PathBuf {
    xdg::state_home().join(NAME)
}
