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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#[cfg(test)]
mod tests;
#[cfg(test)]
mod example;

use std::collections::HashMap;
use std::io;
use std::io::{BufRead, Cursor, Read};
use crate::header::Header;
use crate::ext::string_ext::StringExt;
use crate::http::HTTP;
use crate::symbol::SYMBOL;
use url_build_parse::parse_url;

#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Request {
    pub method: String,
    pub request_uri: String,
    pub http_version: String,
    pub headers: Vec<Header>,
    pub body: Vec<u8>,
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Method {
    pub get: &'static str,
    pub head: &'static str,
    pub post: &'static str,
    pub put: &'static str,
    pub delete: &'static str,
    pub connect: &'static str,
    pub options: &'static str,
    pub trace: &'static str,
    pub patch: &'static str,
}

pub const METHOD: Method = Method {
    get: "GET",
    head: "HEAD",
    post: "POST",
    put: "PUT",
    delete: "DELETE",
    connect: "CONNECT",
    options: "OPTIONS",
    trace: "TRACE",
    patch: "PATCH",
};

impl Request {
    pub const _ERROR_UNABLE_TO_PARSE_METHOD_AND_REQUEST_URI_AND_HTTP_VERSION: &'static str = "Unable to parse method, request uri and http version";

    pub fn get_header(&self, name: String) -> Option<&Header> {
        let header =  self.headers.iter().find(|x| x.name.to_lowercase() == name.to_lowercase());
        header
    }

    pub fn get_domain(&self) -> Result<Option<String>, String> {
        let boxed_host = &self.get_header(Header::_HOST.to_string());
        if boxed_host.is_none() {
            return Ok(None);
        }

        let host_header = boxed_host.unwrap();
        let host = host_header.value.to_string();

        let boxed_host_port = host.split_once(&SYMBOL.colon.to_string());
        if boxed_host_port.is_none() {
            return Ok(Some(host))
        }

        let (domain, _port_str) = boxed_host_port.unwrap();

        Ok(Some(domain.to_string()))
    }

    pub fn get_port(&self) -> Result<Option<i128>, String> {
        let boxed_host = &self.get_header(Header::_HOST.to_string());
        if boxed_host.is_none() {
            return Ok(None);
        }

        let host_header = boxed_host.unwrap();
        let host = host_header.value.to_string();

        let boxed_host_port = host.split_once(&SYMBOL.colon.to_string());
        if boxed_host_port.is_none() {
            return Ok(None)
        }

        let (_domain, port_str) = boxed_host_port.unwrap();

        let boxed_port_i128 = port_str.parse::<i128>();
        if boxed_port_i128.is_err() {
            let message = boxed_port_i128.err().unwrap().to_string();
            return Err(message);
        }

        let port = boxed_port_i128.unwrap();

        Ok(Some(port))
    }

    pub fn get_query(&self) -> Result<Option<HashMap<String, String>>, String> {
        self.get_uri_query()
    }

    pub fn get_uri_query(&self) -> Result<Option<HashMap<String, String>>, String> {
        // it will return an error if unable to parse url
        // it will return None if there are no query params
        // scheme and host required for the parse_url function
        let url_array = ["http://", "localhost/", &self.request_uri];
        let url = url_array.join(SYMBOL.empty_string);

        let boxed_url_components = parse_url(&url);
        if boxed_url_components.is_err() {
            let message = boxed_url_components.err().unwrap().to_string();
            return Err(message)
        }
        Ok(boxed_url_components.unwrap().query)
    }

    pub fn get_path(&self) -> Result<String, String> {
        self.get_uri_path()
    }

    pub fn get_uri_path(&self) -> Result<String, String> {
        // scheme and host required for the parse_url function
        let url_array = ["http://", "localhost", &self.request_uri];
        let url = url_array.join(SYMBOL.empty_string);

        let boxed_url_components = parse_url(&url);
        if boxed_url_components.is_err() {
            let message = boxed_url_components.err().unwrap().to_string();
            return Err(message)
        }
        Ok(boxed_url_components.unwrap().path)
    }

    pub fn method_list() -> Vec<String> {
        let method_get = METHOD.get.to_string();
        let method_head = METHOD.head.to_string();
        let method_post = METHOD.post.to_string();
        let method_put = METHOD.put.to_string();
        let method_delete = METHOD.delete.to_string();
        let method_connect = METHOD.connect.to_string();
        let method_options = METHOD.options.to_string();
        let method_trace = METHOD.trace.to_string();
        let method_patch = METHOD.patch.to_string();

        let method_list = vec![
            method_get,
            method_head,
            method_post,
            method_put,
            method_delete,
            method_connect,
            method_options,
            method_trace,
            method_patch,
        ];

        method_list
    }

    // instance method way to generate a request
    pub fn generate(&self) -> Vec<u8> {
        let clone = self.clone();
        let mut request = Request::_generate_request(clone).as_bytes().to_vec();

        let mut body = self.body.clone();
        request.append(&mut body);

        request
    }

    // same as _generate_request, not renamed original for backward compatability
    pub fn generate_request(request: Request) -> String {
        Request::_generate_request(request)
    }

    pub fn _generate_request(request: Request) -> String {
        let status = [
            request.method,
            request.request_uri,
            request.http_version,
            SYMBOL.new_line_carriage_return.to_string()
        ].join(SYMBOL.whitespace);

        let mut headers = SYMBOL.empty_string.to_string();
        for header in request.headers {
            let mut header_string = SYMBOL.empty_string.to_string();
            header_string.push_str(&header.name);
            header_string.push_str(Header::NAME_VALUE_SEPARATOR);
            header_string.push_str(&header.value);
            header_string.push_str(SYMBOL.new_line_carriage_return);
            headers.push_str(&header_string);
        }

        let request = format!(
            "{}{}{}",
            status,
            headers,
            SYMBOL.new_line_carriage_return
        );


        request
    }

    pub fn parse(request_vec_u8: &[u8]) ->  Result<Request, String> {
        Request::parse_request(request_vec_u8)
    }

    pub fn parse_request(request_vec_u8: &[u8]) ->  Result<Request, String> {
        let mut cursor = io::Cursor::new(request_vec_u8);

        let mut request = Request {
            method: "".to_string(),
            request_uri: "".to_string(),
            http_version: "".to_string(),
            headers: vec![],
            body: vec![],
        };

        let content_length: usize = 0;
        let iteration_number : usize = 0;
        return match Request::cursor_read(&mut cursor, iteration_number, &mut request, content_length) {
            Ok(_) => {
                Ok(request)
            }
            Err(error_message) => {
                Err(error_message)
            }
        }

    }


    pub fn parse_method_and_request_uri_and_http_version_string(http_version_status_code_reason_phrase: &str) -> Result<(String, String, String), String> {
        let lowercase_unparsed_method_and_request_uri_and_http_version = http_version_status_code_reason_phrase.trim();

        let boxed_split_without_method = lowercase_unparsed_method_and_request_uri_and_http_version.split_once(SYMBOL.whitespace);
        if boxed_split_without_method.is_none() {
            return Err(Request::_ERROR_UNABLE_TO_PARSE_METHOD_AND_REQUEST_URI_AND_HTTP_VERSION.to_string())
        }

        let (method, without_method) = boxed_split_without_method.unwrap();
        let supported_methods = Request::method_list();
        if !supported_methods.contains(&method.to_uppercase().to_string()) {
            return Err(Request::_ERROR_UNABLE_TO_PARSE_METHOD_AND_REQUEST_URI_AND_HTTP_VERSION.to_string())
        }

        let boxed_without_method = without_method.split_once(SYMBOL.whitespace);
        if boxed_without_method.is_none() {
            return Err(Request::_ERROR_UNABLE_TO_PARSE_METHOD_AND_REQUEST_URI_AND_HTTP_VERSION.to_string())
        }

        let (request_uri, http_version) = boxed_without_method.unwrap();


        let supported_http_versions = HTTP::version_list();
        if !supported_http_versions.contains(&http_version.to_uppercase().to_string()) {
            return Err(Request::_ERROR_UNABLE_TO_PARSE_METHOD_AND_REQUEST_URI_AND_HTTP_VERSION.to_string())
        }

        Ok((method.to_string(), request_uri.to_string(), http_version.to_string()))

    }

    pub fn parse_http_request_header_string(header_string: &str) -> Header {
        let header_parts: Vec<&str> = header_string.split(Header::NAME_VALUE_SEPARATOR).collect();
        let header_name = StringExt::truncate_new_line_carriage_return(header_parts[0]);
        let mut header_value= "".to_string();
        if header_parts.get(1).is_some() {
            header_value = StringExt::truncate_new_line_carriage_return(header_parts[1]);
        }

        Header {
            name: header_name,
            value: header_value,
        }
    }

    pub fn cursor_read(cursor: &mut Cursor<&[u8]>, mut iteration_number: usize, request: &mut Request, mut content_length: usize) -> Result<bool, String> {
        let mut buf = vec![];
        let bytes_offset = cursor.read_until(b'\n', &mut buf).unwrap();
        let b : &[u8] = &buf;
        let boxed_request = String::from_utf8(Vec::from(b));
        if boxed_request.is_err() {
            let error_message = boxed_request.err().unwrap().to_string();
            return Err(error_message);
        }
        let string = boxed_request.unwrap();

        let is_first_iteration = iteration_number == 0;
        let new_line_char_found = bytes_offset != 0;
        let current_string_is_empty = string.trim().len() == 0;

        if is_first_iteration {
            match Request::parse_method_and_request_uri_and_http_version_string(&string) {
                Ok((method, request_uri, http_version)) => {
                    request.method = method;
                    request.request_uri = request_uri;
                    request.http_version = http_version;
                }
                Err(error_message) => {
                    return Err(error_message)
                }
            }
        }

        if current_string_is_empty {
            return Ok(true);
        }

        if new_line_char_found && !current_string_is_empty {
            let mut header = Header { name: "".to_string(), value: "".to_string() };
            if !is_first_iteration {
                header = Request::parse_http_request_header_string(&string);
                if header.name == Header::_CONTENT_LENGTH {
                    content_length = header.value.parse().unwrap();
                }
            }

            request.headers.push(header);
            iteration_number += 1;
            let boxed_read = Request::cursor_read(cursor, iteration_number, request, content_length);
            if boxed_read.is_err() {
                let reason = boxed_read.err().unwrap().to_string();
                eprintln!("unable to read request: {}", reason);
            }
        }

        // remaining part is request body

        let mut buf = vec![];
        let _ = cursor.read_to_end(&mut buf).unwrap();
        let b : &[u8] = &buf;

        request.body.append(&mut Vec::from(b));// = Vec::from(b);

        Ok(true)
    }

}

impl std::fmt::Display for Request {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(fmt, "Request method {} and request uri {} and http_version {}", self.method, self.request_uri, self.http_version)
    }
}