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

use crate::{ApActivity, ApAddress, ApAnnounce, ApContext, ApFollow, ApLike};
use jdt_maybe_reference::MaybeReference;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub enum ApUndoType {
    #[default]
    #[serde(alias = "undo")]
    Undo,
}

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

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

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

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

impl From<ApFollow> for ApUndo {
    fn from(follow: ApFollow) -> Self {
        ApUndo {
            context: Some(ApContext::default()),
            kind: ApUndoType::default(),
            actor: follow.actor.clone(),
            id: follow.id.clone().map(|follow| format!("{}#undo", follow)),
            object: MaybeReference::Actual(ApActivity::Follow(follow)),
        }
    }
}

impl From<ApAnnounce> for ApUndo {
    fn from(announce: ApAnnounce) -> Self {
        ApUndo {
            context: Some(ApContext::default()),
            kind: ApUndoType::default(),
            actor: announce.actor.clone(),
            id: announce
                .id
                .clone()
                .map(|announce| format!("{}#undo", announce)),
            object: MaybeReference::Actual(ApActivity::Announce(announce)),
        }
    }
}

impl From<ApLike> for ApUndo {
    fn from(like: ApLike) -> Self {
        ApUndo {
            context: Some(ApContext::default()),
            kind: ApUndoType::default(),
            actor: like.actor.clone(),
            id: like.id.clone().map(|like| format!("{}#undo", like)),
            object: MaybeReference::Actual(ApActivity::Like(Box::new(like))),
        }
    }
}
