use crate::common::git::Git;
use std::ffi::OsStr;
use super::rpc::Rpc;

/// Build `commit_header` suitable to pass to `Workspace::new`. Checks the arguments
/// for correctness.
pub fn build_commit_headers(jira: Option<&str>) -> Result<Vec<String>, String> {
    let mut commit_headers = Vec::new();
    if let Some(jira) = jira {
        if !jira.starts_with("http://") && !jira.starts_with("https://") {
            return Err("Invalid JIRA option: please specify the full URL.".to_string());
        }
        commit_headers.push(format!("JIRA: {jira}"));
    }
    Ok(commit_headers)
}

/// Open the upstream and downstream repository. The current directory is assumed to be
/// in the downstream repository. Change the current directory to the root of the downstream
/// repository. If `upstream_repo_path` is None, assume the current directory. Handle errors
/// and return `(upstream_repo, downstream_repo)`.
pub fn open_repos(upstream_repo_path: Option<&OsStr>) -> Result<(Git, Git), String> {
    let upstream_repo = Git::open(match upstream_repo_path {
        Some(path) => path,
        None => OsStr::new("."),
    })
        .map_err(|e| format!("Invalid source git repository path: {e}"))?;
    let downstream_repo = Git::open(OsStr::new("."))
        .map_err(|e| format!("Invalid target git repository path: {e}"))?;
    downstream_repo.chdir()
        .map_err(|e| format!("Cannot chdir to target work tree: {e}"))?;
    Ok((upstream_repo, downstream_repo))
}

/// Create `Rpc` with supplied or default parameters.
pub fn create_rpc(url: Option<String>) -> Rpc {
    Rpc::new(
        url.unwrap_or_else(|| "http://patchpal.usersys.redhat.com:9080/v1".to_string()),
        2,
    )
}
