1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
    }
}