use std::fmt::{Debug, Display, Formatter};

use crate::{ApAddress, ApContext, ApDateTime, ApObject, Ephemeral, Temporal};
use chrono::{DateTime, Utc};
use jdt_maybe_multiple::MaybeMultiple;
use jdt_maybe_reference::MaybeReference;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub enum ApAnnounceType {
    #[default]
    #[serde(alias = "announce")]
    Announce,
}

impl Display for ApAnnounceType {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        Debug::fmt(self, f)
    }
}

#[derive(Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ApAnnounce {
    #[serde(rename = "@context")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<ApContext>,
    #[serde(rename = "type")]
    pub kind: ApAnnounceType,
    pub actor: ApAddress,
    pub id: Option<String>,
    pub to: MaybeMultiple<ApAddress>,
    #[serde(skip_serializing_if = "MaybeMultiple::is_none")]
    #[serde(default)]
    pub cc: MaybeMultiple<ApAddress>,
    pub published: ApDateTime,
    pub object: MaybeReference<ApObject>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub ephemeral: Option<Ephemeral>,
}

impl Debug for ApAnnounce {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Announce[by: {}, obj: {}, at: {}{}]",
            self.actor,
            self.object,
            self.published,
            self.id
                .as_ref()
                .map(|id| format!(", id: {}", id))
                .unwrap_or_default()
        )
    }
}

impl Display for ApAnnounce {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Announce[{}]",
            self.id
                .as_ref()
                .map(|id| format!("id: {}", id))
                .unwrap_or_default()
        )
    }
}

impl Temporal for ApAnnounce {
    fn published(&self) -> String {
        self.published.to_string()
    }

    fn created_at(&self) -> Option<DateTime<Utc>> {
        self.ephemeral.clone().and_then(|x| x.created_at)
    }

    fn updated_at(&self) -> Option<DateTime<Utc>> {
        self.ephemeral.clone().and_then(|x| x.updated_at)
    }
}

impl ApAnnounce {
    pub fn new(object: String, actor: ApAddress, id: Option<String>) -> Self {
        ApAnnounce {
            context: Some(ApContext::activity_streams()),
            kind: ApAnnounceType::default(),
            actor,
            id,
            object: MaybeReference::from(object),
            to: MaybeMultiple::Multiple(vec![ApAddress::get_public()]),
            cc: MaybeMultiple::None,
            published: ApDateTime::now(),
            ephemeral: None,
        }
    }
}
