use std::{net::SocketAddr, str};

use env_logger::Builder;
use log::{info, LevelFilter};
use tokio::io::{AsyncReadExt, AsyncWriteExt, stdin};
use tokio_kcp::{KcpConfig, KcpStream};

#[tokio::main]
async fn main() {
    let mut builder = Builder::new();
    builder.filter_level(LevelFilter::Debug);
    builder.init();

    let config = KcpConfig::default();

    let server_addr = "127.0.0.1:3100".parse::<SocketAddr>().unwrap();

    info!("connect to: {}", server_addr);
    let mut stream = KcpStream::connect(&config, server_addr).await.unwrap();
    info!("connected to server, please input...");

    let mut buffer = [0u8; 8192];
    let mut i = stdin();
    loop {
        let n = i.read(&mut buffer).await.unwrap();
        stream.write_all(&buffer[..n]).await.unwrap();

        let n = stream.read(&mut buffer).await.unwrap();
        println!("{}", unsafe { str::from_utf8_unchecked(&buffer[..n]) });
    }
}