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

use regex::Regex;

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

pub struct DefaultCommandHandlerId(pub TypeId);

impl Deref for DefaultCommandHandlerId {
    type Target = TypeId;

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

#[derive(Clone)]
pub struct CommandHandlerId(pub TypeId);

impl Deref for CommandHandlerId {
    type Target = TypeId;

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

#[derive(Clone)]
pub struct CommandDetectionRegex(pub Regex);

impl Into<CommandDetectionRegex> for Regex {
    fn into(self) -> CommandDetectionRegex {
        CommandDetectionRegex(self)
    }
}

pub trait ICommandHandlerMatchingRule: Sync + Send {
    fn get_command_regex(&self) -> &CommandDetectionRegex;
    fn get_command_handler_id(&self) -> CommandHandlerId;
}

#[derive(Clone)]
pub struct CommandHandlerMatchingRule<TCommandHandler: ICommandHandler + 'static> {
    pub command_regex: CommandDetectionRegex,
    pub pd: PhantomData<TCommandHandler>,
}

impl<TCommandHandler: ICommandHandler + 'static> ICommandHandlerMatchingRule for CommandHandlerMatchingRule<TCommandHandler> {
    fn get_command_regex(&self) -> &CommandDetectionRegex {
        &self.command_regex
    }

    fn get_command_handler_id(&self) -> CommandHandlerId {
        CommandHandlerId(TypeId::of::<TCommandHandler>())
    }
}

impl Deref for CommandDetectionRegex {
    type Target = Regex;

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

#[async_trait_with_sync::async_trait]
pub trait ICommandHandler: Send + Sync {
    async fn handle(&mut self, command: String, request_context: RequestContext) -> CommandResult;
}