use async_trait::async_trait;
use example::base_lib::JRPCResult;
use example::server::{SimpleTestService, SimpleTestServiceHandler};
use example::{JRPCServer, Result, Test2};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::sync::mpsc::channel;

#[derive(Clone)]
struct TestServiceImplementation {}

#[async_trait]
impl SimpleTestService for TestServiceImplementation {
    async fn GetTest(&self, name: String, age: i64) -> Result<Test2> {
        return Ok(Test2 { name, age });
    }

    async fn TestNot(&self) -> Result<()> {
        return Ok(());
    }
}

fn handle_connection(stream: TcpStream, server: &JRPCServer) {
    let (response_sender, mut response_receiver) = channel::<JRPCResult>(1);

    let session = server.get_session(response_sender);

    let (r, mut w) = stream.into_split();
    tokio::spawn(async move {
        loop {
            let res = response_receiver.recv().await;
            match res {
                None => break,
                Some(res) => w
                    .write_all((serde_json::to_string(&res).unwrap() + "\n").as_bytes())
                    .await
                    .unwrap(),
            }
        }
    });

    tokio::spawn(async move {
        let mut reader = BufReader::new(r);
        loop {
            let mut line = String::new();
            let res = reader.read_line(&mut line).await;
            match res {
                Ok(size) => {
                    if size > 0 {
                        session.handle_request(serde_json::from_str(&line).unwrap())
                    } else {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
    });
}

#[tokio::main]
pub async fn main() {
    let mut srv = JRPCServer::new();
    srv.add_service(SimpleTestServiceHandler::new(Box::from(
        TestServiceImplementation {},
    )));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:4321").await.unwrap();

    loop {
        let (stream, address) = listener.accept().await.unwrap();
        println!("Got connection from {}", address);
        handle_connection(stream, &srv);
    }
}
