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
82
83
use crate::requests::*;
use crate::types::*;

pub trait RequestType {
    type Options;
    type Request;

    fn serialize(options: Self::Options, request: &Self::Request) -> Result<HttpRequest, Error>;
}

pub trait ResponseType {
    type Type;

    fn deserialize(resp: HttpResponse) -> Result<Self::Type, Error>;
}

pub trait Request {
    type Type: RequestType;
    type Response: ResponseType + 'static;

    fn serialize(&self) -> Result<HttpRequest, Error>;

    fn detach(&self) -> DetachedRequest<Self::Response> {
        DetachedRequest {
            http_request: self.serialize(),
            phantom: ::std::marker::PhantomData,
        }
    }
}

impl<'a, Req: Request> Request for &'a Req {
    type Type = Req::Type;
    type Response = Req::Response;

    fn serialize(&self) -> Result<HttpRequest, Error> {
        (*self).serialize()
    }
}

impl<'a, Req: Request> Request for &'a mut Req {
    type Type = Req::Type;
    type Response = Req::Response;

    fn serialize(&self) -> Result<HttpRequest, Error> {
        (**self).serialize()
    }
}

pub struct DetachedRequest<Resp> {
    http_request: Result<HttpRequest, Error>,
    phantom: ::std::marker::PhantomData<Resp>,
}

impl<Resp: ResponseType + 'static> Request for DetachedRequest<Resp> {
    type Type = DetachedRequestType;
    type Response = Resp;

    fn serialize(&self) -> Result<HttpRequest, Error> {
        Ok(Self::Type::serialize((), &self.http_request)?)
    }
}

/// Use this trait to convert a complex type to corresponding request and send it to the chat.
pub trait ToRequest<'b> {
    /// Request type.
    type Request: Request;

    /// Convert type to request and send it to the chat.
    fn to_request<C>(&'b self, chat: C) -> Self::Request
    where
        C: ToChatRef;
}

/// Use this trait to convert a complex type to corresponding request and reply to the message.
pub trait ToReplyRequest<'b> {
    /// Request type.
    type Request: Request;

    /// Convert type to request and reply to the message.
    fn to_reply_request<M>(&'b self, message: M) -> Self::Request
    where
        M: ToMessageId + ToSourceChat;
}