/*
SPDX-License-Identifier: GPL-3.0-or-later
Copyright © 2024 Mike Robeson [dijksterhuis]
*/

use std::error::Error;
use std::fmt::Debug;
use std::fs::{create_dir_all, File};
use std::io::Read;
use std::path::{Path, PathBuf};

#[allow(dead_code)]
pub const CRATE_NAME: &str = "ot-tools-io";

#[allow(dead_code)]
pub type RBoxErr<T> = Result<T, Box<dyn Error>>;

#[allow(dead_code)]
pub fn get_blank_proj_dirpath() -> PathBuf {
    PathBuf::from("test-data").join("blank-project")
}

#[allow(dead_code)]
pub fn get_arrange_dirpath() -> PathBuf {
    PathBuf::from("test-data").join("arrange")
}

#[allow(dead_code)]
pub fn get_bank_dirpath() -> PathBuf {
    PathBuf::from("test-data").join("bank")
}

#[allow(dead_code)]
pub fn get_samples_dirpath() -> PathBuf {
    PathBuf::from("test-data").join("samples")
}

#[allow(dead_code)]
pub fn get_project_dirpath() -> PathBuf {
    PathBuf::from("test-data").join("projects")
}

#[allow(dead_code)]
pub fn get_markers_dirpath() -> PathBuf {
    PathBuf::from("test-data").join("markers")
}

#[allow(dead_code)]
pub fn print_and_assert_ok_result<T>(r: RBoxErr<T>)
where
    T: Debug,
{
    println!("{r:?}");
    assert!(r.is_ok());
}

#[allow(dead_code)]
pub fn maybe_create_dir_all(path: &Path) -> RBoxErr<()> {
    if !path.exists() {
        create_dir_all(path)?;
    }
    Ok(())
}

#[allow(dead_code)]
pub fn get_temp_dirpath(dirname: &str) -> PathBuf {
    let path = std::env::temp_dir().join(CRATE_NAME).join(dirname);
    maybe_create_dir_all(&path).unwrap();
    path
}

#[allow(dead_code)]
pub fn read_str_file(path: &Path) -> RBoxErr<String> {
    let mut file = File::open(path)?;
    let mut string = String::new();
    let _ = file.read_to_string(&mut string)?;
    Ok(string)
}
