use diesel::prelude::*;
use internal::{establish_connection, CmdError};
use serenity::{
    framework::standard::{
        macros::{command, group},
        Args, CommandResult,
    },
    model::prelude::Message,
    prelude::Context,
};

use self::{farmed::*, find::*, list::*, update::*};
use models::unit::Unit;

mod farmed;
mod find;
mod list;
mod update;

#[group]
#[prefix = "unit"]
#[description = "Unit related commands"]
#[commands(update, list, find, farmed)]
struct Units;

pub fn find_unit(unit_name: &str, conn: &MysqlConnection) -> Result<Unit, CmdError> {
    use schema::unit::dsl::*;

    let mut units: Vec<Unit> = unit.filter(name.eq(unit_name)).load::<Unit>(conn)?;

    if units.is_empty() {
        units = unit
            .filter(name.like(format!("%{}%", unit_name)))
            .load::<Unit>(conn)?;
    }

    if units.is_empty() {
        Err(CmdError {
            message: format!("No character found for '{}'", unit_name),
        })
    } else if 1 != units.len() {
        let units_list = units
            .into_iter()
            .map(|t| t.name)
            .fold(String::new(), |acc, n| {
                if !acc.is_empty() {
                    acc + ", " + &n
                } else {
                    acc + &n
                }
            });

        Err(CmdError {
            message: format!(
                "More than one character found for '{}'\n{}",
                unit_name, units_list
            ),
        })
    } else {
        Ok(units[0].clone())
    }
}
