use std::{
    io::{BufRead, BufReader},
    process::Command,
};

pub fn modkit(bam_path: &str) {
    // Command to execute your installed CLI application
    let mut cmd = Command::new("modkit");

    // Optionally, you can add arguments to the command
    cmd.arg("summary").arg(bam_path);

    // Spawn the command and obtain a handle to its output
    let mut child = cmd
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start command");

    if let Some(stdout) = child.stdout.take() {
        print_stdout(stdout);
    }

    // let stdout = child.stdout.take().expect("Failed to open stdout");

    // Create a buffer to store the output
    // let mut reader = std::io::BufReader::new(stdout);
    // let mut output = String::new();
    //
    // loop {
    //     // Read the output of the command
    //     match reader.read_line(&mut output) {
    //         Ok(0) => break, // End of output
    //         Ok(_) => {
    //             // Print or process the output here
    //             print!("{}", output);
    //             io::stdout().flush().unwrap();
    //             // print!("{}[2J", 27 as char);
    //             print!("\x1B[2J\x1B[1;1H");
    //
    //             output.clear();
    //         }
    //         Err(err) => {
    //             eprintln!("Error reading from stdout: {}", err);
    //             break;
    //         }
    //     }
    //
    //     // Optionally, you can add a delay to control refresh rate
    //     std::thread::sleep(Duration::from_millis(100));
    // }

    // Wait for the command to finish
    child.wait().expect("Command didn't finish");
}

// fn print_stderr(stderr: std::process::ChildStderr) {
//     let stderr_reader = BufReader::new(stderr);
//     for line in stderr_reader.lines() {
//         match line {
//             Ok(line) => eprintln!("{}", line),
//             Err(err) => eprintln!("Error reading stderr: {}", err),
//         }
//     }
// }
//
fn print_stdout(stdout: std::process::ChildStdout) {
    let stdout_reader = BufReader::new(stdout);
    for line in stdout_reader.lines() {
        match line {
            Ok(line) => eprintln!("{}", line),
            Err(err) => eprintln!("Error reading stderr: {}", err),
        }
    }
}
