use tokio::{
    io::AsyncWriteExt,
    net::{TcpListener, TcpStream},
};

pub(crate) struct TcpServer;

impl TcpServer {
    pub(crate) async fn init() {
        match TcpListener::bind("127.0.0.1:12345").await {
            Ok(listener) => loop {
                match listener.accept().await {
                    Ok((socket, addr)) => {
                        log::info!("New client connected: {addr}");

                        tokio::spawn(async { Self::process(socket).await });
                    }
                    Err(e) => log::error!("Couldn't get client: {e:?}"),
                }
            },
            Err(e) => log::error!("Failed to bind port: {e:?}"),
        }
    }

    async fn process(mut socket: TcpStream) {
        socket
            .write_all("Hello from server written in Rust!".as_bytes())
            .await
            .unwrap();
    }
}
