//! Helper utilities for interacting with the host system.
use std::path::PathBuf;

use anyhow::Result;
use directories::ProjectDirs;

/// The reverse domain name for our application.
const QUALIFIER: &str = "me.anyahope";

/// Our 'organization.'
const ORG: &str = "omry";

/// Our application name.
const APP: &str = "omry-cli";

/// Fallback directory for the config, if `directories` can't get a system default.
const FALLBACK_DIR: &str = ".";

/// Tries to get the OS default [project directories](https://docs.rs/directories/latest/directories/struct.ProjectDirs.html#examples).
/// Uses the current directory if it can't get the standard directory for the OS.
///
/// Returns [`None`] if this function can't get the OS default project dirs, or the current dir.
fn get_project_dirs() -> Option<ProjectDirs> {
    ProjectDirs::from(QUALIFIER, ORG, APP).or_else(|| {
        let cur_path = PathBuf::from(FALLBACK_DIR);
        ProjectDirs::from_path(cur_path)
    })
}

/// Tries to get the [`ProjectDirs`] or return an error.
///
/// This function internally calls [`get_project_dirs`] and converts its return
/// value into a [`Result`].
pub(crate) fn try_get_project_dirs() -> Result<ProjectDirs> {
    get_project_dirs().ok_or_else(|| anyhow::anyhow!("Couldn't get the project dirs"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn can_get_project_dirs() {
        assert!(get_project_dirs().is_some());
    }
}
