use super::*;
use models::{User, UserFarm};
use schema::user::dsl::user;

#[command]
#[aliases("fmd")]
#[description = "List user who farm a unit"]
#[usage = "<UNIT>"]
#[example = "thrawn"]
fn farmed(ctx: &mut Context, msg: &Message, args: Args) -> CommandResult {
    let unit_name = args.rest();

    let conn = establish_connection();

    let unit = find_unit(unit_name, &conn)?;
    let all_users: Vec<User> = user.load(&conn)?;

    let farms: Vec<UserFarm> = UserFarm::belonging_to(&unit).load(&conn)?;

    let users: Vec<String> = farms
        .iter()
        .map(|f| {
            all_users
                .iter()
                .find(|u| u.id == f.user_id)
                .map_or("Unknown".to_string(), |u| u.discord_username.clone())
        })
        .collect();
    let remaining_times: Vec<String> = farms
        .iter()
        .map(|f| {
            f.get_remaining_days()
                .map_or("Unknown".to_string(), |days| days.to_string())
        })
        .collect();

    msg.channel_id.send_message(&ctx.http, |m| {
        m.embed(|e| {
            e.title(format!("Users who farm {}", unit.to_string()))
                .field("User", users.join("\n"), true)
                .field("Remaining days", remaining_times.join("\n"), true)
        })
    })?;

    Ok(())
}
