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 => 1024,
    };

    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::Full(stat) = match Query::get_full(
        address,
        Duration::from_secs(5),
        &mut buffer
    ).await {
        Ok(query) => query,
        Err(err) => {
            eprintln!("{}", err);
            std::process::exit(1);
        }
    } {
        println!("\nFull query response:");
        println!("  KV section: {{");
        for (key, value) in stat.kv {
            println!("    {}: {}", key, value);
        }
        println!("  }}");
        println!("  Players: {}",
            if stat.players.len() > 0 {
                stat.players.join(", ")
            } else {
                "–".to_owned()
            }
        );
        println!("  Software: {}", stat.software.unwrap_or("vanilla".to_owned()));
        print!("  Plugins:");
        match stat.plugins {
            Some(plugins) => {
                println!();
                for plugin in plugins {
                    println!("    {}", plugin);
                }
            },
            None => println!(" –")
        };
    };
}