use crate::{ApAddress, ApContext, ApObject};
use jdt_maybe_multiple::MaybeMultiple;
use jdt_maybe_reference::MaybeReference;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display, Formatter};

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub enum ApLikeType {
    #[default]
    #[serde(alias = "like")]
    Like,
}

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

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

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

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

impl ApLike {
    pub fn new(
        actor: ApAddress,
        to: MaybeMultiple<ApAddress>,
        object: MaybeReference<ApObject>,
        id: Option<String>,
    ) -> Self {
        let context = match object {
            MaybeReference::Reference(_) | MaybeReference::Identifier(_) => {
                Some(ApContext::activity_streams())
            }
            MaybeReference::Actual(_) => Some(ApContext::default()),
            MaybeReference::None => None,
        };

        ApLike {
            context,
            kind: ApLikeType::default(),
            actor,
            id,
            object,
            to,
        }
    }
}
