use std::{
    fs,
    io::{self, Write, stdin, stdout},
    path::PathBuf,
};

use crate::utils::args::Arguments;

pub fn confirm(db_par_dir: &PathBuf, args: &Arguments) -> io::Result<bool> {
    if !db_par_dir.exists() {
        // ask the user if they want to
        // init a new database in target dir
        if !usr_confirm(&args.target_dir)? {
            // no
            println!("No database was created - program cancelled...");
            return Ok(false);
        } else {
            // yes
            fs::create_dir(&db_par_dir)?;
            println!("A new database has been created:");
            println!("{:#?}", db_par_dir);
        }
    }
    Ok(true)
}

pub fn usr_stdin() -> io::Result<String> {
    let mut s = String::new();
    let _ = stdout().flush();
    stdin().read_line(&mut s)?;
    if let Some('\n') = s.chars().next_back() {
        s.pop();
    }
    if let Some('\r') = s.chars().next_back() {
        s.pop();
    }
    Ok(s.to_lowercase().trim().to_string())
}

pub fn usr_confirm(target_dir: &PathBuf) -> io::Result<bool> {
    println!(
        "No database was found. \
        \nDo you want to create one inside this directory?\
        \n\"{}\"\n(y/n)",
        target_dir.display()
    );
    let answer = usr_stdin()?;
    if answer.contains("y") {
        return Ok(true);
    } else {
        return Ok(false);
    }
}
