//! An event
//!
//! The client publishes an events to the relayer
use crate::{common::SerializeDeserialize, types};
use std::{collections::VecDeque, ops::Deref};

/// Publishes an event. It must be signed by a client's public key
#[derive(Debug, Clone)]
pub struct Event(pub types::Event);

impl Deref for Event {
    type Target = types::Event;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<types::Event> for Event {
    fn from(event: types::Event) -> Self {
        Self(event)
    }
}

impl SerializeDeserialize for Event {
    fn get_tag() -> &'static str {
        "EVENT"
    }

    fn serialize(&self) -> Result<Vec<serde_json::Value>, String> {
        Ok(vec![
            serde_json::Value::String(Self::get_tag().to_owned()),
            serde_json::to_value(&self.0).map_err(|e| e.to_string())?,
        ])
    }

    fn deserialize(mut args: VecDeque<serde_json::Value>) -> Result<Self, String>
    where
        Self: Sized,
    {
        Ok(Self(
            serde_json::from_value(args.pop_front().ok_or("Invalid argument length")?)
                .map_err(|e| e.to_string())?,
        ))
    }
}
