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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use std::fmt::Debug;
use serde::{Deserialize, Serialize};
use crate::{
    result::{Result, ElseResponse, ElseResponseWithErr},
    utils::{range::RangeMap, buffer::Buffer},
    components::{json::JSON, status::Status, headers::{HeaderRangeMap, HeaderKey}},
    response::{Response, message::ErrorMessage, body::{Body, ResponseBody}},
};

#[cfg(feature = "sqlx")]
use async_std::sync::Arc;
#[cfg(feature = "postgres")]
use sqlx::PgPool as ConnectionPool;
#[cfg(feature = "mysql")]
use sqlx::MySqlPool as ConnectionPool;

/// Type of context of a HTTP request.
pub struct Context {
    pub req: RequestContext,
    pub(crate) additional_headers: String,

    #[cfg(feature = "sqlx")]
    pub(crate) pool:  Arc<ConnectionPool>,
}
pub struct RequestContext {
    pub(crate) buffer:      Buffer,

    // pub(crate) body:        Option<JSON>,
    pub(crate) query_range: Option<RangeMap>,
    pub(crate) headers:     HeaderRangeMap,
}

impl Context {
    /// Generate `Response` value that represents a HTTP response `200 OK` wrapped in `Ok()`. body:
    /// - `String` | `&str` => `text/plain`
    /// - `JSON` | `Result<JSON>` => `application/json`
    #[allow(non_snake_case)]
    pub fn OK<B: ResponseBody>(&self, body: B) -> Result<Response> {
        Ok(Response {
            additional_headers: self.additional_headers.to_owned(),
            status: Status::OK,
            body: body.as_body()?
        })
    }
    /// Generate `Response` value that represents a HTTP response `201 Created` wrapped in `Ok()`.
    #[allow(non_snake_case)]
    pub fn Created<T: Serialize + for <'d> Deserialize<'d>>(&self, created: JSON<T>) -> Result<Response> {
        Ok(Response {
            additional_headers: self.additional_headers.to_owned(),
            status: Status::Created,
            body: Some(Body::application_json(created.ser()?))
        })
    }
    /// Generate `Response` value that represents a HTTP response `204 No Content` wrapped in `Ok()`.
    #[allow(non_snake_case)]
    pub fn NoContent() -> Result<Response> {
        Ok(Response {
            additional_headers: String::new(),
            status: Status::Created,
            body: None
        })
    }

    /// Generate `Response` value that represents a HTTP response of `404 Not Found`.
    /// `String`, `&str` or `Option<String>` can be argument of this.
    #[allow(non_snake_case)]
    pub fn NotFound<Msg: ErrorMessage>(&self, msg: Msg) -> Response {
        Response {
            additional_headers: self.additional_headers.to_owned(),
            status: Status::NotFound,
            body:   msg.as_message()
        }
    }
    /// Generate `Response` value that represents a HTTP response of `400 Bad Request`.
    /// `String`, `&str` or `Option<String>` can be argument of this.
    #[allow(non_snake_case)]
    pub fn BadRequest<Msg: ErrorMessage>(&self, msg: Msg) -> Response {
        Response {
            additional_headers: self.additional_headers.to_owned(),
            status:             Status::BadRequest,
            body:               msg.as_message(),
        }
    }
    /// Generate `Response` value that represents a HTTP response of `500 Internal Server Error`.
    /// `String`, `&str` or `Option<String>` can be argument of this.
    #[allow(non_snake_case)]
    pub fn InternalServerError<Msg: ErrorMessage>(&self, msg: Msg) -> Response {
        Response {
            additional_headers: self.additional_headers.to_owned(),
            status:             Status::InternalServerError,
            body:               msg.as_message(),
        }
    }
    /// Generate `Response` value that represents a HTTP response of `501 Not Implemented`.
    /// `String`, `&str` or `Option<String>` can be argument of this.
    #[allow(non_snake_case)]
    pub fn NotImplemented<Msg: ErrorMessage>(&self, msg: Msg) -> Response {
        Response {
            additional_headers: self.additional_headers.to_owned(),
            status:             Status::NotImplemented,
            body:               msg.as_message(),
        }
    }
    /// Generate `Response` value that represents a HTTP response of `403 Forbidden`.
    /// `String`, `&str` or `Option<String>` can be argument of this.
    #[allow(non_snake_case)]
    pub fn Forbidden<Msg: ErrorMessage>(&self, msg: Msg) -> Response {
        Response {
            additional_headers: self.additional_headers.to_owned(),
            status:             Status::Forbidden,
            body:               msg.as_message(),
        }
    }
    /// Generate `Response` value that represents a HTTP response of `401 Unauthorized`.
    /// `String`, `&str` or `Option<String>` can be argument of this.
    #[allow(non_snake_case)]
    pub fn Unauthorized<Msg: ErrorMessage>(&self, msg: Msg) -> Response {
        Response {
            additional_headers: self.additional_headers.to_owned(),
            status:             Status::Unauthorized,
            body:               msg.as_message(),
        }
    }

    /// Add response header of `{key}: {value}`. key: &'static str | Header
    pub fn header<Key: HeaderKey>(&mut self, key: Key, value: &'static str) {
        self.additional_headers += key.as_key_str();
        self.additional_headers += ": ";
        self.additional_headers += value;
        self.additional_headers += "\n"
    }

    /// Return a reference of `PgPool` (if feature = "postgres") or `MySqlPool` (if feature = "mysql").
    #[cfg(feature = "sqlx")]
    pub fn pool(&self) -> &ConnectionPool {
        &*self.pool
    }
}
impl<'d> RequestContext {
    /*
        /// Try deserialize the reuqest body into Rust struct that implements `serde::Deserialize`, and return `Result</* that struct */>`. If request doesn't have body, this returns `Err(Response)` of "Bad Request".
        pub fn body<D: Deserialize<'d>>(&'d self) -> Result<D> {
            let json = self.body.as_ref()
                ._else(|| Response::BadRequest("expected request body"))?;
            let json_struct = json.to_struct()?;
            Ok(json_struct)
        }
    */
    
    /// Return `Result< &str | u8 | u64 | i32 | i64 | usize >` that holds query parameter whose key matches the argument (`Err`: if param string can't be parsed).
    /// ```no_run
    /// let count = ctx.query("count")?;
    /// ```
    pub fn query<'ctx, Q: Query<'ctx>>(&'ctx self, key: &str) -> Result<Q> {
        Query::parse(
            self.query_range
                .as_ref()
                ._else(|| Response::BadRequest(format!("expected query param `{key}`")))?
                .read_match_part_of_buffer(key, &self.buffer)
                ._else(|| Response::BadRequest(format!("expected query param `{key}`")))?
        )
    }

    /// Get value of the request header if it exists. key: &'static str | Header
    pub fn header<K: HeaderKey>(&self, key: K) -> Result<&str> {
        let key_str = key.as_key_str();
        self.headers.get(key_str, &self.buffer)
            ._else(|| Response::InternalServerError(
                format!("Header `{}` was not found", key_str)
            ))
    }
}

pub trait Query<'q> {fn parse(q: &'q str) -> Result<Self> where Self: Sized;}
impl<'q> Query<'q> for &'q str {fn parse(q: &'q str) -> Result<Self> {Ok(q)}}
impl<'q> Query<'q> for u8 {fn parse(q: &'q str) -> Result<Self> {q.parse()._else(|_| Response::BadRequest("format of query parameter is wrong"))}}
impl<'q> Query<'q> for u64 {fn parse(q: &'q str) -> Result<Self> {q.parse()._else(|_| Response::BadRequest("format of query parameter is wrong"))}}
impl<'q> Query<'q> for i64 {fn parse(q: &'q str) -> Result<Self> {q.parse()._else(|_| Response::BadRequest("format of query parameter is wrong"))}}
impl<'q> Query<'q> for i32 {fn parse(q: &'q str) -> Result<Self> {q.parse()._else(|_| Response::BadRequest("format of query parameter is wrong"))}}
impl<'q> Query<'q> for usize {fn parse(q: &'q str) -> Result<Self> {q.parse()._else(|_| Response::BadRequest("format of query parameter is wrong"))}}

impl Debug for Context {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "query: {:?} (range: {:?}), {}",
            self.req.query_range.as_ref().map(|map| map.debug_fmt_with(&self.req.buffer)),
            self.req.query_range,
            self.req.headers.debug_fmt_with(&self.req.buffer),
        )
    }
}


#[cfg(test)]
mod test {
    #[test]
    fn how_str_as_ptr_works() {
        assert_eq!("abc".as_ptr(), "abc".as_ptr());

        let abc = "abc";
        let abc2 = "abc";
        assert_eq!(abc.as_ptr(), abc2.as_ptr());

        let string = String::from("abcdef");
        // let string2 = String::from("abcdef");
        assert_eq!(string, "abcdef");
    }

}