use serde::{Deserialize, Serialize};

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

#[derive(Serialize, Deserialize, Extract)]
pub struct Options {
    name: String,
}

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 count = Timer::count_from_owner(owner, &ctx.data().database).await;

        if count >= 25 {
            ctx.say(
                "You already have 25 timers. Please delete some timers before creating a new one",
            )
            .await?;
        } else if self.name.len() <= 32 {
            Timer::create(&self.name, owner, &ctx.data().database).await;

            ctx.say("Created a new timer").await?;
        } else {
            ctx.say(format!(
                "Please name your timer something shorted (max. 32 characters, you used {})",
                self.name.len()
            ))
            .await?;
        }

        Ok(())
    }
}

/// Start a new timer from now
#[poise::command(
    slash_command,
    rename = "start",
    identifying_name = "start_timer",
    default_member_permissions = "MANAGE_GUILD"
)]
pub async fn start(
    ctx: Context<'_>,
    #[description = "Name for the new timer"] name: String,
) -> Result<(), Error> {
    (Options { name }).run(ctx).await
}
