use chrono::{DateTime, Utc};
use num_integer::Integer;
use poise::{serenity_prelude::CreateEmbed, CreateReply};
use serde::{Deserialize, Serialize};

use crate::{
    consts::THEME_COLOR,
    models::timer::Timer,
    utils::{Extract, Recordable},
    Context, Error,
};

fn time_difference(start_time: DateTime<Utc>) -> String {
    let delta = (Utc::now() - start_time).num_seconds();

    let (minutes, seconds) = delta.div_rem(&60);
    let (hours, minutes) = minutes.div_rem(&60);
    let (days, hours) = hours.div_rem(&24);

    format!("{} days, {:02}:{:02}:{:02}", days, hours, minutes, seconds)
}

#[derive(Serialize, Deserialize, Extract)]
pub struct Options;

impl Recordable for Options {
    async fn run(self, ctx: Context<'_>) -> Result<(), Error> {
        let owner = ctx.guild_id().map(|g| g.get()).unwrap_or_else(|| ctx.author().id.get());

        let timers = Timer::from_owner(owner, &ctx.data().database).await;

        if !timers.is_empty() {
            ctx.send(
                CreateReply::default().embed(
                    CreateEmbed::new()
                        .fields(timers.iter().map(|timer| {
                            (
                                &timer.name,
                                format!("⌚ `{}`", time_difference(timer.start_time)),
                                false,
                            )
                        }))
                        .color(*THEME_COLOR),
                ),
            )
            .await?;
        } else {
            ctx.say("No timers currently. Use `/timer start` to create a new timer").await?;
        }

        Ok(())
    }
}

/// List the timers in this server or DM channel
#[poise::command(
    slash_command,
    rename = "list",
    identifying_name = "list_timer",
    default_member_permissions = "MANAGE_GUILD"
)]
pub async fn list(ctx: Context<'_>) -> Result<(), Error> {
    (Options {}).run(ctx).await
}
