use std::io::{Error, ErrorKind};

use telnet::Telnet;

use crate::cli::Commands;

mod wrappers;
mod commands;
mod parameter;
mod cli;
mod utils;
mod models;
mod response;
mod command_utils;

fn result_or_error<T>(res: Result<Option<T>, String>, result_type: &str) -> Result<T, Error> {
    let error_action = format!("find {}", result_type);
    res.map_err(|err| make_action_error(&error_action, err))?
        .ok_or_else(|| make_action_error(&error_action, String::from("Not Found.")))
}

fn connect() -> Result<Telnet, Error> {
    let mut connection = Telnet::connect(("127.0.0.1", 25639), 512 * 1024)
        .map_err(|_| Error::new(ErrorKind::AddrNotAvailable, String::from("Failed to connect to Teamspeak.")))?;

    wrappers::skip_welcome(&mut connection)
        .map_err(to_other_error)?;
    wrappers::login(&mut connection)
        .map_err(|msg| Error::new(ErrorKind::PermissionDenied, msg))?;

    Ok(connection)
}

fn to_other_error(msg: String) -> Error {
    Error::new(ErrorKind::Other, msg)
}

fn make_action_error(action: &str, msg: String) -> Error {
    Error::new(ErrorKind::Other, format!("Failed to {}: {}", action, msg))
}

fn main() -> Result<(), Error> {
    let cli = cli::init();

    let mut connection = connect()?;

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    match cli {
        Commands::Channels(args) => {
            match wrappers::get_channels(&mut connection, args.spacers) {
                Ok(channels) => {
                    for channel in channels {
                        println!("{}", channel.channel_name);
                    }
                }
                Err(msg) => {
                    return Err(make_action_error("get channels", msg));
                }
            }
        }

        Commands::Clients => {
            match wrappers::get_clients(&mut connection) {
                Ok(clients) => {
                    for client in clients {
                        println!("{}", client.client_nickname);
                    }
                }
                Err(msg) => {
                    return Err(make_action_error("get clients", msg));
                }
            }
        }

        Commands::Fetch(args) => {
            if args.want_client() && args.want_channel() {
                return Err(Error::new(ErrorKind::InvalidInput, "Fetching both clients and channels is not supported."));
            }
            if !args.want_client() && !args.want_channel() {
                return Err(Error::new(ErrorKind::InvalidInput, "No clients or channels specified."));
            }

            if args.want_client() {
                let client = result_or_error(args.client(&mut connection), "client")?;

                match wrappers::fetch_client(&mut connection, &[client]) {
                    Ok(_) => println!("Successfully fetched client."),
                    Err(msg) => {
                        return Err(make_action_error("fetch client", msg));
                    }
                }
            }

            if args.want_channel() {
                let channel = result_or_error(args.channel(&mut connection), "channel")?;

                match wrappers::fetch_channel(&mut connection, channel) {
                    Ok(_) => println!("Successfully fetched channel."),
                    Err(msg) => {
                        return Err(make_action_error("fetch channel", msg));
                    }
                }
            }
        }

        Commands::Message(args) => {
            let target = args.target(&mut connection)
                .map_err(|msg| make_action_error("message target", msg))?;

            match wrappers::send_text_message(&mut connection, target, args.message) {
                Ok(_) => println!("Successfully sent message."),
                Err(msg) => {
                    return Err(make_action_error("send message", msg));
                }
            }
        }

        Commands::Move(args) => {
            let channel = result_or_error(args.channel(&mut connection), "channel")?;
            let client = result_or_error(args.client(&mut connection), "client")?;

            match wrappers::move_client(&mut connection, &channel, &[client]) {
                Ok(resp) => println!("Successfully moved client: {}", resp),
                Err(msg) => {
                    return Err(make_action_error("move client", msg));
                }
            }
        }

        Commands::Update(args) => {
            match wrappers::update_client(&mut connection, args.to_parameter_list()) {
                Ok(_) => println!("Successfully updated client."),
                Err(msg) => {
                    return Err(make_action_error("update client", msg));
                }
            }
        }

        Commands::Events(args) => {
            loop {
                command_utils::events::register_events(&mut connection, args.event.clone())
                    .map_err(to_other_error)?;

                command_utils::events::loop_response_reader(&mut connection);

                // loop_response_reader failed. Let's try to reconnect after 1 second.
                std::thread::sleep(std::time::Duration::from_secs(1));
                connection = connect()?;
            }
        }
    }
    Ok(())
}