use std::process;

use crate::text;

// ping a host
pub fn latency_test(address: &str, count: &u16, interval: &u16) {
    println!("Pinging host {}, {} times.", address, count);

    // if we're on Windows we need to use the -n flag for ping counts
    let mut count_arg = "-c";
    if cfg!(windows) {
        count_arg = "-n";
    }

    // convert the ping interval to seconds
    let interval_secs = *interval as f64 / 1000 as f64;

    // run the ping command
    let output = process::Command::new("ping")
        .arg(address)
        .arg(count_arg)
        .arg(format!("{}", count))
        .arg("-i")
        .arg(format!("{}", interval_secs))
        .output()
        .expect("Failed to execute command");

    // check that the command succeeded
    assert!(output.status.success());

    // grab the ping results from stdout
    let results_raw = &String::from_utf8_lossy(&output.stdout);
    let results = text::format::trim_output(results_raw, 4);
    for line in results {
        println!("{}", line);
    }
}

// network jitter test
pub fn jitter_test(address: &str, count: &u16, interval: &u16) {
    println!("Pinging host {}, {} times to determine network jitter.", address, count);

    // if we're on Windows we need to use the -n flag for ping counts
    let mut count_arg = "-c";
    if cfg!(windows) {
        count_arg = "-n";
    }

    // convert the ping interval to seconds
    let interval_secs = *interval as f64 / 1000 as f64;

    // run the ping command
    let output = process::Command::new("ping")
        .arg(address)
        .arg(count_arg)
        .arg(format!("{}", count))
        .arg("-i")
        .arg(format!("{}", interval_secs))
        .output()
        .expect("Failed to execute command");

    // check that the command succeeded
    assert!(output.status.success());

    // grab the ping results from stdout
    let results_raw = &String::from_utf8_lossy(&output.stdout);
    let results = text::format::trim_output(results_raw, 4);
    for line in results {
        println!("{}", line);
    }
}

// timed file copy test to guage bandwidth speeds
pub fn bandwidth_test(host: &str) {
    println!("Testing network bandwidth using iperf; connecting to {}.", host);
    println!("{}", host);

    let output = process::Command::new("iperf3")
        .arg("-c")
        .arg(host)
        .output()
        .expect("Failed to execute command");

    // check that the command succeeded
    assert!(output.status.success());

    // grab and print the command's results
    let results_raw = &String::from_utf8_lossy(&output.stdout);
    println!("{}", results_raw);
}