use std::ffi::{OsStr, OsString};

pub fn parse_command(command_text: &str) -> (String, Vec<String>) {
    let words: Vec<&str> = command_text.split(' ').collect();
    let mut name = "".to_string();
    let mut args = Vec::new();
    if words.len() > 0 {
        name = words[0].to_string();
        if words.len() > 1 {
            for i in 1..words.len() {
                args.push(words[i].to_string());
            }
        }
    }

    // test for file with content similar to:
    // #! ruby
    // #!/bin/bash
    match super::paths::Paths::which(&name) {
        Ok(path) => match super::paths::Paths::shebang(&path) {
            Ok(shebang) => match super::paths::Paths::which(&shebang) {
                Ok(_) => {
                    let name2 = shebang;
                    let mut args2 = Vec::new();
                    args2.push(path.display().to_string());
                    for arg in args {
                        args2.push(arg);
                    }
                    return (name2, args2);
                }
                Err(_) => {}
            },
            Err(_) => {}
        },
        Err(_) => {}
    }

    (name, args)
}

pub fn get_vec_osstring<I, S>(args: I) -> Vec<OsString>
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let mut results = Vec::new();
    for arg in args.into_iter() {
        let s: &OsStr = arg.as_ref();
        results.push(s.to_os_string());
    }
    results
}

#[cfg(test)]
#[test]
fn parse_command_test() {
    match super::Env::which("rake") {
        Ok(_) => {
            let (name, args) = parse_command("rake default");
            assert!(name.contains("rake"), "{} did not contains 'rake'", name);
            assert_eq!(1, args.len(), "args: {:?}", args)
        }
        Err(_) => {}
    }
}
