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

pub const NOXIS_RS_CREDS: &str = "127.0.0.1:7753";


pub async fn create_tcp_stream() -> Result<TcpStream> {
    Ok(TcpStream::connect(NOXIS_RS_CREDS).await.map_err(|_| NoxisCliError::NoxisDaemonMissing)?)
}

pub async fn try_send(stream: Result<TcpStream>, params: Cli) -> Result<()> {
    use serde_json::to_string;
    let mut stream = stream.map_err(|_| NoxisCliError::NoxisDaemonMissing)?;
    loop {
        if stream.writable().await.is_err() {
            sleep(Duration::from_millis(100)).await;
            continue;
        }
        // let msg: Cli = from_str(&format!("{:?}", params))?;
        let msg= to_string(&params).map_err(|_| NoxisCliError::ToStringCliParsingParsing)?;
        // let msg = r"HTTP/1.1 POST\r\nContent-Length: 14\r\nContent-Type: text/plain\r\n\r\nHello, World!@";

        stream.write_all(msg.as_bytes()).await.map_err(|_| NoxisCliError::CliPromptCanNotBeSent)?;
        // ...
        break;
    }
    Ok(())
}