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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// a context extends hashmap to provide some extra functionality
//

use hyper::Request;
use serde::{Deserialize, Serialize};
use std::{any::Any, collections::HashMap, mem::ManuallyDrop, sync::Arc};

use crate::{
    server::{uri::ToParams, Method, NgynRequest, NgynResponse, Transformer},
    traits::NgynController,
};

/// Represents the value of a context in Ngyn
#[derive(Serialize, Deserialize)]
struct NgynContextValue<V> {
    value: V,
}

impl<V> NgynContextValue<V> {
    pub fn create(value: V) -> Self {
        Self { value }
    }
}

/// Represents the state of an application in Ngyn
pub trait AppState: Any + Send + Sync {
    fn as_any(&self) -> &dyn Any
    where
        Self: Sized,
    {
        self
    }
}

impl AppState for Arc<dyn AppState> {}

pub struct EmptyState;
impl AppState for EmptyState {}

/// Represents the context of a request in Ngyn
pub struct NgynContext {
    request: Request<Vec<u8>>,
    params: Option<Vec<(String, String)>>,
    route_info: Option<(String, Arc<Box<dyn NgynController>>)>,
    store: HashMap<String, String>,
    state: Option<Arc<dyn AppState>>,
}

impl NgynContext {
    /// Retrieves the request associated with the context.
    ///
    /// # Returns
    ///
    /// A reference to the request associated with the context.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    /// use hyper::Request;
    ///
    /// let request = Request::new(Vec::new());
    /// let context = NgynContext::from_request(request);
    ///
    /// let request_ref = context.request();
    /// ```
    pub fn request(&self) -> &Request<Vec<u8>> {
        &self.request
    }

    /// Retrieves the params associated with the context.
    ///
    /// # Returns
    ///
    /// An optional reference to the params associated with the context.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".into());
    ///
    /// let params_ref = context.params();
    /// ```
    pub fn params(&self) -> Option<&Vec<(String, String)>> {
        self.params.as_ref()
    }
}

impl NgynContext {
    /// Retrieves the state of the context as a reference to the specified type.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The type of the state to retrieve.
    ///
    /// # Returns
    ///
    /// An optional reference to the state of the specified type. Returns `None` if the state is not found or if it cannot be downcasted to the specified type.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set_state(Box::new(MyAppState::new()));
    ///
    /// let state_ref = context.state::<MyAppState>();
    /// ```
    pub fn state<T: 'static>(&self) -> Option<&T> {
        let state = self.state.as_ref();

        match state {
            Some(value) => value.as_any().downcast_ref::<T>(),
            None => None,
        }
    }
}

impl NgynContext {
    /// Retrieves the value associated with the given key from the context.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to retrieve the value for.
    ///
    /// # Returns
    ///
    /// A reference to the value associated with the key. If the key is not found, returns a reference to an empty context value.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".into());
    ///
    /// let value: String = context.get("name").unwrap();
    /// assert_eq!(value, "John".to_string());
    /// ```
    pub fn get<V: for<'a> Deserialize<'a>>(&self, key: &str) -> Option<V> {
        let value = self.store.get(key.to_lowercase().trim());
        match value {
            Some(v) => {
                let stored_cx: NgynContextValue<V> = serde_json::from_str(v).unwrap();
                Some(stored_cx.value)
            }
            None => None,
        }
    }

    /// Sets the value associated with the given key in the context.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to set the value for.
    /// * `value` - The value to associate with the key.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".into());
    ///
    /// let value: String = context.get("name").unwrap();
    /// assert_eq!(value, "John".to_string());
    /// ```
    pub fn set<V: Serialize>(&mut self, key: &str, value: V) {
        self.store.insert(
            key.trim().to_lowercase(),
            serde_json::to_string(&NgynContextValue::create(value)).unwrap(),
        );
    }

    /// Removes the value associated with the given key from the context.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to remove the value for.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".into());
    ///
    /// context.remove("name");
    /// let value = context.get::<String>("name");
    /// assert_eq!(value, None);
    /// ```
    pub fn remove(&mut self, key: &str) {
        self.store.remove(key.to_lowercase().trim());
    }

    /// Clears all values from the context.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".into());
    /// context.set("age", 30.into());
    ///
    /// context.clear();
    /// assert_eq!(context.len(), 0);
    /// ```
    pub fn clear(&mut self) {
        self.store.clear();
    }

    /// Returns the number of values in the context.
    ///
    /// # Returns
    ///
    /// The number of values in the context.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".into());
    /// context.set("age", 30.into());
    ///
    /// assert_eq!(context.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.store.len()
    }

    /// Checks if the context is empty.
    ///
    /// # Returns
    ///
    /// `true` if the context is empty, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    ///
    /// assert!(context.is_empty());
    ///
    /// context.set("name", "John".into());
    /// assert!(!context.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.store.is_empty()
    }

    /// Checks if the context contains a value for the given key.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to check for.
    ///
    /// # Returns
    ///
    /// `true` if the context contains a value for the key, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".into());
    ///
    /// assert!(context.has("name"));
    /// assert!(!context.has("age"));
    /// ```
    pub fn has(&self, key: &str) -> bool {
        self.store.contains_key(key.to_lowercase().trim())
    }
}

impl NgynContext {
    /// Creates a new `NgynContext` from the given request.
    ///
    /// # Arguments
    ///
    /// * `request` - The request to create the context from.
    ///
    /// # Returns
    ///
    /// A new `NgynContext` instance.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    /// use hyper::Request;
    ///
    /// let request = Request::new(Vec::new());
    /// let context = NgynContext::from_request(request);
    /// assert!(context.is_empty());
    /// ```
    pub(crate) fn from_request(request: Request<Vec<u8>>) -> Self {
        NgynContext {
            request,
            store: HashMap::new(),
            params: None,
            route_info: None,
            state: None,
        }
    }

    pub(crate) fn set_state(&mut self, state: Arc<dyn AppState>) {
        self.state = Some(state);
    }

    /// Sets the route information for the context.
    ///
    /// # Arguments
    ///
    /// * `path` - The path of the route.
    /// * `method` - The HTTP method of the route.
    ///
    /// # Returns
    ///
    /// If the method of the request matches the given method and the path matches the route, returns a mutable reference to the context. Otherwise, returns `None`.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    /// use ngyn_shared::Method;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".into());
    ///
    /// let result = context.with("/users", &Method::GET);
    /// assert!(result.is_none());
    ///
    /// let result = context.with("/users", &Method::POST);
    /// assert!(result.is_some());
    /// ```
    pub(crate) fn with(&mut self, path: &str, method: &Method) -> Option<&mut Self> {
        if method.ne(self.request.method()) {
            return None;
        }
        if let Some(params) = self.request.uri().to_params(path) {
            self.params = Some(params);
            Some(self)
        } else {
            None
        }
    }

    /// Checks if the context has a valid route.
    /// A valid route is when the route information and the params are set.
    /// This is great for differentiating known routes from unknown routes.
    ///
    /// # Returns
    ///
    /// `true` if the context has a valid route, `false` otherwise.
    pub fn is_valid_route(&self) -> bool {
        self.params.is_some()
    }

    /// Prepares the context for execution by setting the route information.
    ///
    /// # Arguments
    ///
    /// * `controller` - The controller to handle the request.
    /// * `handler` - The handler to execute.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    /// use ngyn_shared::NgynController;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// let controller = MyController::new();
    ///
    /// context.prepare(Box::new(controller), "index".to_string());
    /// ```
    pub(crate) fn prepare(&mut self, controller: Arc<Box<dyn NgynController>>, handler: String) {
        self.route_info = Some((handler, controller));
    }

    /// Executes the handler associated with the route in the context.
    ///
    /// # Arguments
    ///
    /// * `res` - The response to write to.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    /// use ngyn_shared::NgynResponse;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// let mut response = NgynResponse::new();
    ///
    /// context.execute(&mut response).await;
    /// ```
    pub(crate) async fn execute(&mut self, res: &mut NgynResponse) {
        let (handler, controller) = match self.route_info.take() {
            Some((handler, ctrl)) => (handler, ctrl),
            None => return,
        };
        let mut controller =
            ManuallyDrop::<Box<dyn NgynController>>::new(controller.clone().into());
        controller.handle(&handler, self, res).await;
    }
}

impl<'a> Transformer<'a> for &'a NgynContext {
    fn transform(cx: &'a mut NgynContext, _res: &'a mut NgynResponse) -> Self {
        cx
    }
}

impl<'a> Transformer<'a> for &'a mut NgynContext {
    fn transform(cx: &'a mut NgynContext, _res: &'a mut NgynResponse) -> Self {
        cx
    }
}

impl<'a> Transformer<'a> for &'a NgynRequest {
    fn transform(cx: &'a mut NgynContext, _res: &'a mut NgynResponse) -> Self {
        cx.request()
    }
}

impl Transformer<'_> for NgynRequest {
    fn transform(cx: &mut NgynContext, _res: &mut NgynResponse) -> Self {
        cx.request().clone()
    }
}