use mcquery::Query;
use std::{
    time::Duration,
    env
};

#[tokio::main]
async fn main() {
    let buffer_size = match env::args().nth(3) {
        Some(arg) => match arg.parse() {
            Ok(size) => size,
            Err(err) => {
                eprintln!("Error parsing buffer size");
                eprintln!("{}", err);
                std::process::exit(1);
            },
        },
        None => 128,
    };

    println!("Creating {}B buffer...", buffer_size);
    let mut buffer = vec![0; buffer_size];

    let address = (
        match env::args().nth(1) {
            Some(ip) => ip,
            None => {
                eprintln!("No server IP specified");
                std::process::exit(1);
            },
        }, match env::args().nth(2).unwrap_or("25565".to_owned()).parse() {
            Ok(port) => port,
            Err(err) => {
                eprintln!("Error parsing port");
                eprintln!("{}", err);
                std::process::exit(1);
            },
        }
    );
    println!("Connecting with {}:{}...", address.0, address.1);

    if let Query::Basic(stat) = match Query::get_basic(
        address,
        Duration::from_secs(5),
        &mut buffer
    ).await {
        Ok(query) => query,
        Err(err) => {
            eprintln!("{}", err);
            std::process::exit(1);
        }
    } {
        println!("\nBasic query response:");
        println!("  MOTD: {}", stat.motd);
        println!("  Map: {}", stat.map);
        println!("  Players: {}/{}", stat.num_players, stat.max_players);
        println!("  Host: {}:{}", stat.ip, stat.port);
    };
}