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
use std::{usize, str::FromStr};
use std::str;



use log::info;

use crate::{http::errors::malformed::MalformedError, Verb};
#[derive(PartialEq, Debug, Clone)]

pub struct HTTPRequest {
    pub start_line: StartLine,
    pub header: Option<Headers>,
    pub body: Option<Body>
}

#[derive(PartialEq, Debug, Clone)]
pub struct StartLine{
    pub verb: Verb,
    pub ressource: String
}

type Headers = Vec<(String, String)>;
type Body = String;



impl TryFrom<[u8; 1024]> for HTTPRequest {
    type Error = MalformedError;
    fn try_from(value: [u8; 1024]) -> Result<Self, MalformedError> {
        return str::from_utf8(&value)
        .map_err(|error| 
            MalformedError::from(error))
        .map(|request| 
            HTTPRequest::try_from(request))?
    }
}

impl TryFrom<&str> for HTTPRequest {
    type Error = MalformedError;
    fn try_from(buffer: &str) -> Result<Self, MalformedError> {

        let parsed_request = parse(buffer);
        
        let start_line = get_start_line(parsed_request.clone())?;
        info!("Ressource: {}", start_line.ressource);
        
        let headers = extract_headers(parsed_request.clone());
        info!("Headers: {:?}", headers);

        let content_length = get_content_length(headers.clone())?;
        info!("Content-Length: {}", content_length.to_string());

        let body = extract_body(parsed_request, content_length);
        info!("Body: {}", body);

        return Ok (HTTPRequest { start_line: start_line, header: Some(headers), body: Some(body)});
    }
}


fn extract_body(request : Vec<String>, content_length: usize) -> Body {
    return request.iter()
            .skip_while(|&str| str.trim() != "")
            .fold("".to_owned(), |acc, e| acc + e + "\r\n")
            .to_string()
            .drain(0..content_length)
            .collect();
}

fn get_start_line(request : Vec<String>) -> Result<StartLine, MalformedError> {
    return request.iter()
        .next()
        .map(|start_line| StartLine::try_from((*start_line).clone()))
        .unwrap_or(Err(MalformedError::from("Need start line")))
}

fn parse(buffer : &str) -> Vec<String> {
    return buffer
        .trim_matches(char::from(0))
        .split("\r\n")
        .map(|str| str.to_string())
        .collect::<Vec<String>>();
}

impl TryFrom<Vec<String>> for StartLine {
    type Error = MalformedError;
    fn try_from(request: Vec<String>) -> Result<Self, Self::Error> {
        return request.iter()
            .next()
            .map(|start_line| StartLine::try_from((*start_line).clone()))
            .unwrap_or(Err(MalformedError::from("Need start line")));
    }
}

fn get_content_length(headers: Headers) -> Result<usize, MalformedError> {
    return headers
        .iter()
        .find(|(header, _)| header.starts_with("Content-Length:"))
        .map(|(_, value)| 
            (*value).parse::<usize>()
            .map_err(MalformedError::from))
        .transpose()
        .map(|length| length.unwrap_or(0));

}

fn extract_headers(request : Vec<String>) -> Headers {
    return request.iter()
        .skip(1)
        .take_while(|&str| str.trim() != "")
        .map(|header| {
            let mut line = header.split_ascii_whitespace();
            return match line.next() {
                None => None,
                Some(str)=> Some((str.to_string(), line.next().unwrap_or("").to_string())) 
            }
        })
        .filter(|line| line.is_some())
        .flatten()
        .collect::<Headers>();
}




impl TryFrom<String> for StartLine {
    type Error = MalformedError;
        fn try_from(value: String) -> Result<Self, MalformedError> {
            let binding = value
                .split(' ')
                .take(3).collect::<Vec<&str>>();
            let mut decomposed_start_line =  binding
                .iter();
            
            let verb = decomposed_start_line
                .next()
                .ok_or(MalformedError::from("Missing verb"))
                .map(|&verb| Verb::from_str(verb))??;


            let ressource = decomposed_start_line
                .next()
                .ok_or(MalformedError::from("No ressource"))
                .map(|&str| str.to_string())?;

            return Ok(StartLine { verb: verb, ressource: ressource });
}
    
}



// UNIT TEST
#[cfg(test)]
mod tests {
    use std::vec;

    use super::*;



    #[test]
    fn request_try_from_ok() {
        let buffer = "POST rappel/1 HTTP/1.1\r\nContent-Length: 4\r\n\r\ntoto";
        
        let  request = HTTPRequest::try_from(buffer);
        
        let http_request = request.unwrap();
        assert_eq!(http_request.start_line, StartLine{verb: Verb::POST, ressource: "rappel/1".to_string()});
        assert_eq!(http_request.body, Some("toto".to_string()));
        assert_eq!(http_request.header, Some(vec![("Content-Length:".to_string(), "4".to_string())]))
    }

    #[test]
    fn request_try_from_ko() {
        let buffer = "POST rappel/1 HTTP/1.1\r\nContent-Length: 4\r\n\r\ntoto";
        
        let  request = HTTPRequest::try_from(buffer);
        
        assert!(request.is_ok());
    }

    #[test]
    fn extract_body_ok() {
        let request = vec!["POST rappel/1 HTTP/1.1".to_string()," ".to_string(),"toto".to_string(), "toto".to_string()];
        
        let  request = extract_body(request, 8);
        
        assert_eq!(request, "totototo");
    }

    #[test]
    fn extract_headers_ok() {
        let request = vec!["ressource".to_string(),"Content-Length: 1".to_string(),"Content-type: x".to_string(), "".to_string()];
        
        let  request = extract_headers(request);
        
        assert_eq!(request, vec![("Content-Length:".to_string(), "1".to_string()),("Content-type:".to_string(), "x".to_string())]);
    }

    #[test]
    fn get_content_length_ok() {
        let headers = vec![("Content-Length:".to_string(), "152".to_string()),("Content-type:".to_string(), "x".to_string())];

        let content_length = get_content_length(headers);
        
        assert_eq!(content_length, Ok(152));
    }

    #[test]
    fn get_content_length_ko_malformed() {
        let headers = vec![("Content-Length:".to_string(), "152a".to_string()),("Content-type:".to_string(), "x".to_string())];

        let content_length = get_content_length(headers);
        
        assert_eq!(content_length, Err(MalformedError::from("Expected a valid integer")));
    }

    #[test]
    fn get_content_length_ok_0() {
        let headers = vec![("Content-type:".to_string(), "x".to_string())];

        let content_length = get_content_length(headers);
        
        assert_eq!(content_length, Ok(0));
    }

    


}