use crate::options::structs::CustomError;
use log::{error, warn};
use std::io;
use std::process::{Command, Output};
use std::sync::Arc;
use tokio::time::Duration;

pub async fn get_pid(name: &str) -> Option<Output> {
    let name = Arc::new(name.to_string());
    let res =
        // todo : unwrap change - can be unsafe
        tokio::task::spawn_blocking(move || Command::new("pidof").arg(&*name).output()).await.unwrap();
    if let Ok(output) = res {
        if output.stderr.is_empty() && output.stdout.is_empty() {
            None
        } else {
            Some(output)
        }
    } else {
        None
    }
}
// ! can be with bug !!!
// * APPROVED
pub async fn is_active(name: &str) -> bool {
    let arc_name = Arc::new(name.to_string());
    tokio::task::spawn_blocking(move || {
        let output = Command::new("pidof")
            .arg(&*arc_name)
            .output()
            .unwrap_or_else(|_| {
                error!("Failed to execute command 'pidof'");
                std::process::exit(101);
            });
        !String::from_utf8_lossy(&output.stdout).trim().is_empty()
    })
    .await
    .unwrap()
}

// T is for stopped processes
pub async fn is_frozen(name: &str) -> bool {
    let temp: Output;
    if let Some(output) = get_pid(name).await {
        temp = output;
    } else {
        return false;
    }
    let pid = String::from_utf8_lossy(&temp.stdout);
    let pid = pid.trim();
    let arc_pid = Arc::new(pid.to_string());
    if pid.is_empty() {
        false
    } else {
        tokio::task::spawn_blocking(move || {
            let cmd = Command::new("ps")
                .args(["-o", "stat=", "-p", &arc_pid])
                .output()
                .unwrap_or_else(|_| {
                    error!("Failed to execute ps command");
                    std::process::exit(101);
                });
            String::from_utf8_lossy(&cmd.stdout).contains("T")
        })
        .await
        .unwrap()
    }
}
pub async fn terminate_process(name: &str) {
    let _ = Command::new("pkill")
        .arg(name)
        .output()
        .unwrap_or_else(|_| {
            error!("Failed to execute command 'pkill'");
            std::process::exit(101);
        });
}

pub async fn freeze_process(name: &str) {
    let _ = Command::new("pkill")
        .args(["-STOP", name])
        .output()
        .unwrap_or_else(|_| {
            error!("Failed to freeze process");
            std::process::exit(101);
        });
}
pub async fn unfreeze_process(name: &str) {
    let _ = Command::new("pkill")
        .args(["-CONT", name])
        .output()
        .unwrap_or_else(|_| {
            error!("Failed to unfreeze process");
            std::process::exit(101);
        });
}
pub async fn restart_process(name: &str, path: &str) -> Result<(), CustomError> {
    terminate_process(name).await;
    tokio::time::sleep(Duration::from_millis(100)).await;
    start_process(name, path).await
}

pub async fn start_process(name: &str, path: &str) -> Result<(), CustomError> {
    // let runsh = format!("{} {}", "exec", path);
    let mut command = Command::new(path);
    // command.arg(path);

    match command.spawn() {
        Ok(_) => {
            warn!("Process {} is running now!", name);
            Ok(())
        }
        Err(er) => {
            println!("{:?}", er);
            Err(CustomError::Fatal)
        }
    }
}

#[cfg(test)]
mod process_unittests {
    use super::*;
    // 1 full cycle - start -> restart -> stop
    // 2 full cycle - start -> freeze -> unfreze -> stop
    // 2x is active
    // 2x is frozen
    // 2x pidof

    // rewrite, its a pipe
    #[tokio::test]
    async fn full_cycle_with_restart() {
        let res1 = start_process("temp-process", "/home/user/monitor/runner-rs/temp-process").await;
        assert!(res1.is_ok());
        let res2 =
            restart_process("temp-process", "/home/user/monitor/runner-rs/temp-process").await;
        assert!(res2.is_ok());
        let _ = terminate_process("temp-process").await;
        let res3 = is_active("temp-process").await;
        assert!(res3);
    }
    // rewrite, its a pipe
    #[tokio::test]
    async fn full_cycle_with_freeze() {
        assert!(true);
    }
    #[tokio::test]
    async fn is_active_check() {
        assert!(is_active("systemd").await);
    }
    #[tokio::test]
    async fn isnt_active_check() {
        assert!(!is_active("invalid-process-name").await);
    }
    #[tokio::test]
    async fn is_frozen_check() {
        assert!(!is_frozen("systemd").await);
    }
    #[tokio::test]
    async fn pidof_active_process() {
        assert!(get_pid("systemd").await.is_some());
    }

    // broken mechanism need to check
    #[tokio::test]
    async fn pidof_disabled_process() {
        assert!(get_pid("invalid-process-name").await.is_none());
    }
}
