use std::net::{TcpListener, TcpStream};
use std::io::prelude::*;
mod client;
mod conf;
mod protocol;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:25567").unwrap();
    let mut buf: [u8; 256] = [1; 256];
    let servers = conf::Servers::new();

    for stream in listener.incoming() {
        //stream.unwrap().write(buf);
        match stream {
            Ok(mut stream) => {
                /*println!("Go!");
                stream.write("test succes/n".as_bytes());
                stream.read(&mut buf);
                stream.flush();*/
                println!("Go!");
                let leng = stream.read(&mut buf).unwrap();
                let mut hs = protocol::HandShake::new(&mut buf[.. leng]);
                if hs.get_raw()[0] < 200 {
                    let mut sstream;
                    
                    if hs.get_raw()[6]==49 {
                        //buf[(buf[0]-1) as usize] -= 2;
                        println!("p0:{}",hs.get_port());
                        hs.replace_port(servers.get_server(&hs.getHostName()).unwrap().1);
                        println!("p1:{}",hs.get_port());
                        sstream = TcpStream::connect("127.0.0.1:25565").unwrap();
                    } else {
                        println!("p0:{}",hs.get_port());
                        match servers.get_server(&hs.getHostName()) {
                            Some(s) => hs.replace_port(s.1),
                            None => hs.replace_port(25565),
                        }
                        println!("p1:{}",hs.get_port());
                        sstream = TcpStream::connect("127.0.0.1:25566").unwrap();
                    }
                    //let mut sstream = TcpStream::connect("127.0.0.1:25565").unwrap();
                    sstream.write(hs.get_raw());
                    let c1 = client::Client::new(stream,sstream, hs);
                    c1.to_string();
                    c1.start_proxy();
                }
                //c1.start_proxy().0.join();
                //c1.start_proxy().1.join();
                },

            Err(_e) => println!("{}",_e),
        }
    }
}

