use crate::error::JournalError;
use log::debug;
use std::ffi::OsString;
use std::path::Path;
use std::process::Command;

pub fn init<P: AsRef<Path>>(dirname: P) -> Result<(), JournalError> {
    let dirname = dirname.as_ref();
    debug!("git init {}", dirname.display());

    let output = Command::new("git")
        .arg("init")
        .current_dir(dirname)
        .output()
        .map_err(|err| JournalError::SpawnGit(dirname.to_path_buf(), err))?;
    debug!("git init exit code was {:?}", output.status.code());
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
        return Err(JournalError::GitInit(dirname.to_path_buf(), stderr));
    }
    Ok(())
}

pub fn add<P: AsRef<Path>>(dirname: P, files: &[P]) -> Result<(), JournalError> {
    let args = &["add", "--"];
    let mut args: Vec<OsString> = args.iter().map(OsString::from).collect();
    for f in files {
        args.push(OsString::from(f.as_ref()));
    }

    let dirname = dirname.as_ref();
    debug!("git add in {}", dirname.display());

    let output = Command::new("git")
        .args(&args)
        .current_dir(dirname)
        .output()
        .map_err(|err| JournalError::SpawnGit(dirname.to_path_buf(), err))?;
    debug!("git exit code was {:?}", output.status.code());
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
        return Err(JournalError::GitAdd(dirname.to_path_buf(), stderr));
    }
    Ok(())
}

pub fn commit<P: AsRef<Path>>(dirname: P, msg: &str) -> Result<(), JournalError> {
    let dirname = dirname.as_ref();
    debug!("git commit in {}", dirname.display());

    let output = Command::new("git")
        .args(["commit", "-m", msg])
        .current_dir(dirname)
        .output()
        .map_err(|err| JournalError::SpawnGit(dirname.to_path_buf(), err))?;
    debug!("git exit code was {:?}", output.status.code());
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
        return Err(JournalError::GitCommit(dirname.to_path_buf(), stderr));
    }
    Ok(())
}
