use std::fs;
use std::fs::read_to_string;
use std::io::Write;
use std::path::PathBuf;
use std::process;
use crate::Project;

pub fn run_initial_enum(project: &Project){
    let mut csv = String::new();
    println!("path to the csv?");
    std::io::stdin().read_line(&mut csv).unwrap();
    let status = process::Command::new("initial_recon").arg(&csv).arg(&project.customer).arg(&project.project_name).status().expect("error running initial_recon program");
    if status.success(){
        println!("execllent! hosts should be imported to {}/host_notes.md", &project.notes_folder.display());
    }
    else{
        println!("ooof something went wrong, host notes may not have saved correctly!");
    }
}

pub fn build_cmd_for_host_discovery(project: &Project){
    let mut cobalt_strike_response = String::new();
    let mut need_shell = false;
    println!("will you be running this via cobalt strike? (do you need it to start with \"shell\"?");
    let input_result = std::io::stdin().read_line(&mut cobalt_strike_response);
    if input_result.is_err(){
        println!("error getting user input... not really sure how you did this... just pressing enter would work..... wow");
        return;
    }
    if cobalt_strike_response.to_lowercase().contains("y"){
        need_shell = true;
    }
    let mut general_note_path = project.notes_folder.clone();
    general_note_path.push("general.md");
    println!("Reading from: {}", general_note_path.display());
    let mut ranges = Vec::new();
    let general_note_string = read_to_string(general_note_path);
    let mut _note_string = String::new();
   match general_note_string{
        Err(error) => {println!("error reading file to string!! {}", error); return;},
        _=> _note_string = general_note_string.unwrap()
    }
    let lines: Vec<&str> = _note_string.split("\n").collect();
    for line in lines{
       if line.contains("|"){
            if line.contains("."){
                let ip = line.split("|").collect::<Vec<&str>>()[1];
                if ip .contains(","){
                    let ips: Vec<&str> = ip.split(",").collect();
                    for ip in ips{
                        ranges.push(ip.trim_end().trim_start());
                    }
                } 
                else{
                    ranges.push(ip.trim_end().trim_start());
                }
            }
        }
    }
    let mut _discovery_command = "";
    _discovery_command = "(for /L %a IN (1,1,254) DO ping /n 1 /w 3 !!!.%a) | find \"Reply\"";
    let mut final_command = String::new();
    for range in ranges{
        let mut network: Vec<&str> = range.split(".").collect();
        network.pop();
        let network_string = network.join(".");
        let mut _range_command = String::new();
        if need_shell{
            _range_command = format!("{}{}","shell ", _discovery_command.replace("!!!", &network_string));
            need_shell = false;
        }
        else{
            _range_command = _discovery_command.replace("!!!", &network_string);
        }
        final_command.push_str(_range_command.as_str());
        final_command.push_str(">> ping_only_replies.txt &");
    }
    final_command.pop();
    println!("{}", final_command);
}

pub fn generate_userpass(project: &Project){
    let mut outlines = Vec::new();
    let mut notes_file = project.notes_folder.clone();
    notes_file.push("l00t/creds.md");
    let loot_string = fs::read_to_string(notes_file).expect("error reading creds note");
    let clear_text = loot_string.split("# hashed").collect::<Vec<&str>>()[0];
    let clear_text_table = clear_text.split("| ----------------------------------- | ------------- | ----------------------------- |").collect::<Vec<&str>>()[1];
    let table_vec: Vec<&str> = clear_text_table.split("\n").collect();
    for line in table_vec{
        if line.len() > 1{
            let split_line: Vec<&str> = line.split("|").collect();
            let user = split_line[2].trim_end().trim_start();
            let password = split_line[3].trim_end().trim_start();
            let outline = format!("{}:{}\n", user, password);
            outlines.push(outline);
        }
    }
    let mut out_file_path = project.files_folder.clone();
    out_file_path.push("working/userpass_fromnotes.txt");
    let mut out_file = fs::File::create(out_file_path).expect("error creating userpass file");
    for line in outlines{
        out_file.write_all(line.as_bytes()).expect("error writing to userpass file");
    }
}

pub fn open_in_dolphin(folder: &str, project: Project){
    let mut to_open = PathBuf::new();
    match folder{
        "notes" => to_open.push(project.notes_folder),
        "files" => to_open.push(project.files_folder),
        _ => println!("unknown entry... this should literally be impossible... how.... how tf did you.... what")
    }
    process::Command::new("dolphin")
                         .arg(to_open)
                         .spawn().expect("error opening dolphin");
}

pub fn print_report_information(project: Project){
    let mut general_notes_path = project.notes_folder.clone();
    let mut finding_notes_path = project.notes_folder.clone();
    general_notes_path.push("general.md ");
    finding_notes_path.push("findings.md ");
    println!("general: {}\nfindings: {}", general_notes_path.display(), finding_notes_path.display());
    let  general_string = fs::read_to_string(general_notes_path).expect("error opening general notes");
    let  findings_string = fs::read_to_string(finding_notes_path).expect("error opening findings notes");
    let general_lines: Vec<&str> = general_string.split("\n").collect();
    let finding_lines: Vec<&str> = findings_string.split("\n").collect();
    println!("Scope:");
    for line in general_lines{
        if line.contains("|"){
            let split: Vec<&str> = line.split("|").collect();
            println!("{}\t{}", split[0], split[2]);
        }
    }
    println!("Findings");
    for line in finding_lines{
        if line.contains("# "){
            println!("{}", line);
        }
        else if line.contains("- "){
            println!("{}", line)
        }
    }
    
}