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
use crate::makepad_micro_serde::*;
use crate::makepad_live_id::*;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::collections::BTreeMap;
use std::str;
use crate::event::Event;

#[derive(Clone, Debug)]
pub struct NetworkResponseEvent {
    pub request_id: LiveId,
    pub response: NetworkResponse,
}

#[derive(Clone, Debug)]
pub enum NetworkResponse{
    HttpRequestError(String),
    HttpResponse(HttpResponse),
    HttpProgress{loaded:u32, total:u32},
    WebSocketClose,
    WebSocketOpen,
    WebSocketError(String),
    WebSocketString(String),
    WebSocketBinary(Vec<u8>)
}

pub struct NetworkResponseIter<I> {
    iter: Option<I>,
}

impl<I> Iterator for NetworkResponseIter<I> where I: Iterator {
    type Item = I::Item;
    
    fn next(&mut self) -> Option<I::Item> {
        match &mut self.iter{
            None=>None,
            Some(v)=>v.next()
        }
    }
}

impl Event{
    pub fn network_responses(&self) -> NetworkResponseIter<std::slice::Iter<'_, NetworkResponseEvent>>{
        match self{
            Event::NetworkResponses(responses)=>{
                NetworkResponseIter{
                    iter:Some(responses.iter())
                }
            }
            _=>{
                // return empty thing
                NetworkResponseIter{iter:None}
            }
        } 
    }
}

pub struct NetworkResponseChannel {
    pub receiver: Receiver<NetworkResponseEvent>,
    pub sender: Sender<NetworkResponseEvent>,
}

impl Default for NetworkResponseChannel {
    fn default() -> Self {
        let (sender, receiver) = channel();
        Self {
            sender,
            receiver
        }
    }
}


#[derive(PartialEq, Debug)]
pub struct HttpRequest {
    pub metadata_id: LiveId,
    pub url: String,
    pub method: HttpMethod,
    pub headers: BTreeMap<String, Vec<String>>,
    pub body: Option<Vec<u8>>,
}

impl HttpRequest { 
    pub fn new(url: String, method: HttpMethod) -> Self {
        HttpRequest {
            metadata_id: LiveId(0),
            url,
            method,
            headers: BTreeMap::new(),
            body: None
        }
    }
    
    pub fn set_metadata_id(&mut self, id: LiveId){
        self.metadata_id = id;
    }
    
    pub fn set_header(&mut self, name: String, value: String) {
        let entry = self.headers.entry(name).or_insert(Vec::new());
        entry.push(value);
    }

    pub fn get_headers_string(&self) -> String {
        let mut headers_string = String::new();
        for (key, value) in self.headers.iter() {
            headers_string.push_str(&format!("{}: {}\r\n", key, value.join(",")));
        }
        headers_string
    }

    pub fn set_body(&mut self, body: Vec<u8>) {
        self.body = Some(body);
    }

    pub fn set_body_string(&mut self, v: &str) {
        self.body = Some(v.as_bytes().to_vec());
    }

    pub fn set_json_body<T: SerJson>(&mut self, body: T) {
       let json_body = body.serialize_json();
       let serialized_body = json_body.into_bytes();
       self.body = Some(serialized_body); 
    }

    pub fn set_string_body(&mut self, body: String) {
        self.body = Some(body.into_bytes());
    }
}

#[derive(Debug, Clone)]
pub struct HttpResponse {
    pub metadata_id: LiveId,
    pub status_code: u16,
    pub headers: BTreeMap<String, Vec<String>>,
    pub body: Option<Vec<u8>>,
}

impl HttpResponse {
    pub fn new(metadata_id: LiveId, status_code: u16, string_headers: String, body: Option<Vec<u8>>) -> Self {
        HttpResponse {
            metadata_id,
            status_code,
            headers: HttpResponse::parse_headers(string_headers),
            body
        }
    }

    pub fn set_header(&mut self, name: String, value: String) {
        let entry = self.headers.entry(name).or_insert(Vec::new());
        entry.push(value);
    }

    pub fn get_body(&self) -> Option<&Vec<u8>> {
        self.body.as_ref()
    }

    pub fn get_string_body(&self) -> Option<String> {
        if let Some(body) = self.body.as_ref() {
            if let Ok(utf8) = String::from_utf8(body.to_vec()){
                return Some(utf8)
            }
        }
        None
    }

    // Todo: a more generic function that supports serialization into rust structs from other MIME types
    pub fn get_json_body<T: DeJson>(&self) -> Result<T, DeJsonErr> { 
        if let Some(body) = self.body.as_ref() {
            let json = str::from_utf8(&body).unwrap();
            DeJson::deserialize_json(&json)
        } else {
            Err(DeJsonErr{
                msg:"No body present".to_string(),
                line:0,
                col:0
            })
        }
    }

    fn parse_headers(headers_string: String) -> BTreeMap<String, Vec<String>> {
        let mut headers = BTreeMap::new();
        for line in headers_string.lines() {
            let mut split = line.split(":");
            let key = split.next().unwrap();
            let values = split.next().unwrap().to_string();
            for val in values.split(",") {
                let entry = headers.entry(key.to_string()).or_insert(Vec::new());
                entry.push(val.to_string());
            }
        }
        headers
    }
}

#[derive(PartialEq, Debug)]
pub enum HttpMethod{
    GET,
    HEAD,
    POST,
    PUT,
    DELETE,
    CONNECT,
    OPTIONS,
    TRACE,
    PATCH
}

impl HttpMethod {
    pub fn to_string(&self) -> &str {
        match self {
            Self::GET => "GET",
            Self::HEAD => "HEAD",
            Self::POST => "POST",
            Self::PUT => "PUT",
            Self::DELETE => "DELETE",
            Self::CONNECT => "CONNECT",
            Self::OPTIONS => "OPTIONS",
            Self::TRACE => "TRACE",
            Self::PATCH => "PATCH",
        }
    }
}