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 ApFollowType {
    #[default]
    #[serde(alias = "follow")]
    Follow,
}

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

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

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

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

impl ApFollow {
    pub fn new(object: String, actor: ApAddress, id: Option<String>) -> Self {
        ApFollow {
            id,
            context: Some(ApContext::activity_streams()),
            kind: ApFollowType::Follow,
            actor,
            object: object.into(),
            ..Default::default()
        }
    }
}
