use tokio::net::UnixStream;
use tokio::io::{AsyncWriteExt, AsyncReadExt};
use tokio::time::{Duration, sleep};
use anyhow::Result;
use super::Cli;
use super::cli_error::NoxisCliError;

async fn create_us_stream(cli: &Cli) -> Result<UnixStream> {
    Ok(UnixStream::connect(&cli.socket).await.map_err(|er| NoxisCliError::NoxisDaemonMissing((&cli.socket).to_string(), er.to_string()))?)
}

pub async fn try_send(cli: Cli) -> Result<()> {
    // let stream = create_us_stream(&cli).await;
    let mut stream = create_us_stream(&cli).await?;

    let msg = serde_json::to_vec(&cli)
        .map_err(|_| NoxisCliError::ToStringCliParsingParsing)?;

    stream.write_all(&msg)
        .await
        .map_err(|_| NoxisCliError::CliPromptCanNotBeSent)?;

    let mut response = [0; 1024];
    stream.read(&mut response)
        .await
        .map_err(|er| NoxisCliError::CliResponseReadError(er.to_string()))?;

    println!("Received response: {}", String::from_utf8_lossy(&response));
    Ok(())
}