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
use std::{any::{Any, TypeId}, marker::PhantomData, ops::Deref};

use anthill_di::{*, types::BuildDependencyResult};
use serde::Deserialize;

use crate::{contexts::RequestContext, results::CommandResult};

pub struct InternalBotNotificationHandlerTypeId(pub TypeId);

impl Deref for InternalBotNotificationHandlerTypeId {
    type Target = TypeId;

    fn deref(&self) -> &Self::Target { &self.0 }
}

#[async_trait_with_sync::async_trait]
pub trait IInternalBotNotificationHandler: Send + Sync {
    type TData: Sync + Send + for<'de> Deserialize<'de> + 'static;
    type TOptions: Sync + Send + for<'de> Deserialize<'de> + 'static;

    async fn handle(&mut self, data: Self::TData, options: Self::TOptions, request_context: RequestContext) -> CommandResult;
}

pub trait IInternalBotNotificationDataProcessor: 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) -> InternalBotNotificationHandlerTypeId;
}

/// Десериализует данные и если удалось возвращает не типизированную ссылку на данные
pub struct InternalBotNotificationDataProcessor<THandler: IInternalBotNotificationHandler + 'static> {
    handler_pd: PhantomData<THandler>
}

impl<THandler: IInternalBotNotificationHandler + 'static> IInternalBotNotificationDataProcessor for InternalBotNotificationDataProcessor<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) -> InternalBotNotificationHandlerTypeId {
        InternalBotNotificationHandlerTypeId(TypeId::of::<THandler>())
    }
}

#[async_trait_with_sync::async_trait(Sync)]
impl<THandler: IInternalBotNotificationHandler + 'static> Constructor for InternalBotNotificationDataProcessor<THandler> {
    async fn ctor(_: DependencyContext) -> BuildDependencyResult<Self> {
        Ok(Self { handler_pd: Default::default() })
    }
}

/// Возвращает тип данным и вызывает обработчик
#[async_trait_with_sync::async_trait]
pub trait IInternalBotNotificationCallProducer: Send + Sync {
    async fn handle(&mut self, data: Box<dyn Any + Sync + Send>, options: Box<dyn Any + Sync + Send>, request_context: RequestContext) -> CommandResult;
}

#[async_trait_with_sync::async_trait]
impl<T: IInternalBotNotificationHandler + 'static> IInternalBotNotificationCallProducer for T
{
    async fn handle(&mut self, 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, data, options, request_context).await
    }
}