use std::{any::{TypeId, Any}, ops::Deref, marker::PhantomData};
use anthill_di::{*, types::BuildDependencyResult};
use serde::Deserialize;
use uuid::Uuid;
use crate::{contexts::RequestContext, results::CommandResult};
pub struct SmartappEventHandlerTypeId(pub TypeId);
impl Deref for SmartappEventHandlerTypeId {
type Target = TypeId;
fn deref(&self) -> &Self::Target { &self.0 }
}
#[async_trait_with_sync::async_trait]
pub trait ISmartappEventHandler: Sync + Send {
type TData: Sync + Send + for<'de> Deserialize<'de> + 'static;
type TOptions: Sync + Send + for<'de> Deserialize<'de> + 'static;
async fn handle(&mut self, request_ref: Uuid, smartapp_id: Uuid, smartapp_api_version: u16, data: Self::TData, options: Self::TOptions, request_context: RequestContext) -> CommandResult;
}
pub trait ISmartappEventDataProcessor: Sync + Send {
fn get_data(&self, data: &serde_json::Value) -> Option<Box<dyn Any + Sync + Send>>;
fn get_options(&self, options: &serde_json::Value) -> Option<Box<dyn Any + Sync + Send>>;
fn get_handler_type_id(&self) -> SmartappEventHandlerTypeId;
}
pub struct SmartappEventDataProcessor<THandler: ISmartappEventHandler + 'static> {
handler_pd: PhantomData<THandler>
}
impl<THandler: ISmartappEventHandler + 'static> ISmartappEventDataProcessor for SmartappEventDataProcessor<THandler> {
fn get_data(&self, data: &serde_json::Value) -> Option<Box<dyn Any + Sync + Send>> {
serde_json::value::from_value::<THandler::TData>(data.clone())
.map(|x| Box::new(x) as Box<dyn Any + Sync + Send>)
.ok()
}
fn get_options(&self, options: &serde_json::Value) -> Option<Box<dyn Any + Sync + Send>> {
serde_json::value::from_value::<THandler::TOptions>(options.clone())
.map(|x| Box::new(x) as Box<dyn Any + Sync + Send>)
.ok()
}
fn get_handler_type_id(&self) -> SmartappEventHandlerTypeId {
SmartappEventHandlerTypeId(TypeId::of::<THandler>())
}
}
#[async_trait_with_sync::async_trait(Sync)]
impl<THandler: ISmartappEventHandler + 'static> Constructor for SmartappEventDataProcessor<THandler> {
async fn ctor(_: DependencyContext) -> BuildDependencyResult<Self> {
Ok(Self { handler_pd: Default::default() })
}
}
#[async_trait_with_sync::async_trait]
pub trait ISmartappEventCallProducer: Send + Sync {
async fn handle(&mut self, request_ref: Uuid, smartapp_id: Uuid, smartapp_api_version: u16, data: Box<dyn Any + Sync + Send>, options: Box<dyn Any + Sync + Send>, request_context: RequestContext) -> CommandResult;
}
#[async_trait_with_sync::async_trait]
impl<T: ISmartappEventHandler + 'static> ISmartappEventCallProducer for T
{
async fn handle(&mut self, request_ref: Uuid, smartapp_id: Uuid, smartapp_api_version: u16, data: Box<dyn Any + Sync + Send>, options: Box<dyn Any + Sync + Send>, request_context: RequestContext) -> CommandResult {
let data = unsafe {
*data.downcast_unchecked::<T::TData>()
};
let options = unsafe {
*options.downcast_unchecked::<T::TOptions>()
};
T::handle(self, request_ref, smartapp_id, smartapp_api_version, data, options, request_context).await
}
}