// module needed to check host-agent health condition and to communicate with it
/// asdasdasds
use tokio::{io::Interest, net::UnixStream};

async fn open_unix_socket() -> Result<UnixStream, std::io::Error> {
    let socket = UnixStream::connect("/var/run/enode/hostagent.sock").await?;
    Ok(socket)
}

async fn ha_healthcheck(socket: &UnixStream) -> Result<(), std::io::Error >{
    socket.ready(Interest::WRITABLE).await?;
    if socket.writable().await.is_ok() {
        if let Err(er) = socket.try_write(b"Hello HAgent") {
            return Err(er);
        }
    } else {
        return Err(std::io::ErrorKind::WouldBlock.into());
    }
    Ok(())
}


async fn ha_send_data(socket: &UnixStream, data: &str) -> Result<(), std::io::Error > {
    socket.ready(Interest::WRITABLE).await?;
    if socket.writable().await.is_ok() {
        if let Err(er) = socket.try_write(data.as_bytes()) {
            return Err(er);
        }
    } else {
        return Err(std::io::ErrorKind::WouldBlock.into());
    }
    Ok(())
}

#[cfg(test)]
mod hagent_unittets {
    use super::*;
    #[tokio::test]
    // maybe bool : true -> alive, false -> dead
    // simple request on api
    async fn hagent_healthcheck() {
        let sock = open_unix_socket().await;
        assert!(sock.is_ok());
        let sock = sock.unwrap();
        assert!(ha_healthcheck(&sock).await.is_ok());
    }
    #[tokio::test]
    // --Result<maybe Response>
    // one-shot func
    async fn send_metrics_to_hagent() {
        use crate::options::structs::{ProcessMetrics, ContainerMetrics, Metrics};
        
        let procm = ProcessMetrics::new("test-prc", 15.0, 5.0);
        let contm = ContainerMetrics::new("test", 32.0, 12.0, vec![procm.process_name.clone()]);
        let metrics = Metrics::new(contm, vec![procm]);
        let metrics = &serde_json::to_string_pretty(&metrics).unwrap();

        let sock = open_unix_socket().await;
        assert!(sock.is_ok());
        let sock = sock.unwrap();
        assert!(ha_healthcheck(&sock).await.is_ok());
        assert!(ha_send_data(&sock, &metrics).await.is_ok());

    }
    #[tokio::test]
    async fn open_unixsocket_test() {
        assert!(open_unix_socket().await.is_ok());
    }
}
