Documentation
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Copyright 2024 The Drasi Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime};
use core::fmt::{self, Debug, Display};
use drasi_query_ast::ast::Expression as AstExpression;
use duration::Duration;
use float::Float;
use index::Index;
use integer::Integer;
use serde_json::Value;
use std::{
    collections::BTreeMap,
    hash::{Hash, Hasher},
    sync::Arc,
};
use zoned_datetime::ZonedDateTime;
use zoned_time::ZonedTime;

use crate::models::{Element, ElementMetadata, ElementReference};

#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Clone, Hash, Eq, Default)]
pub enum VariableValue {
    #[default]
    Null,
    Bool(bool),
    Float(Float),
    Integer(Integer),
    String(String),
    List(Vec<VariableValue>),
    Object(BTreeMap<String, VariableValue>), //Do we need our own map type?

    Date(NaiveDate), //NaiveDate does not support TimeZone, which is consistent with Neo4j's documentation
    LocalTime(NaiveTime),
    ZonedTime(ZonedTime),
    LocalDateTime(NaiveDateTime), // no timezone info
    ZonedDateTime(ZonedDateTime),
    Duration(Duration),
    Expression(AstExpression),
    ListRange(ListRange),
    Element(Arc<Element>),
    ElementMetadata(ElementMetadata),
    ElementReference(ElementReference),
    Awaiting,
}

impl From<VariableValue> for Value {
    fn from(val: VariableValue) -> Self {
        match val {
            VariableValue::Null => Value::Null,
            VariableValue::Bool(b) => Value::Bool(b),
            VariableValue::Float(f) => Value::Number(f.into()),
            VariableValue::Integer(i) => Value::Number(i.into()),
            VariableValue::String(s) => Value::String(s),
            VariableValue::List(l) => Value::Array(l.into_iter().map(|x| x.into()).collect()),
            VariableValue::Object(o) => {
                Value::Object(o.into_iter().map(|(k, v)| (k, v.into())).collect())
            }
            VariableValue::Date(d) => Value::String(d.to_string()),
            VariableValue::LocalTime(t) => Value::String(t.to_string()),
            VariableValue::ZonedTime(t) => Value::String(t.to_string()),
            VariableValue::LocalDateTime(t) => Value::String(t.to_string()),
            VariableValue::ZonedDateTime(t) => Value::String(t.to_string()),
            VariableValue::Duration(d) => Value::String(d.to_string()),
            VariableValue::Expression(e) => Value::String(format!("{e:?}")),
            VariableValue::ListRange(r) => Value::String(r.to_string()),
            VariableValue::Element(e) => e.as_ref().into(),
            VariableValue::ElementMetadata(m) => Value::String(m.to_string()),
            VariableValue::ElementReference(r) => Value::String(r.to_string()),
            VariableValue::Awaiting => Value::String("Awaiting".to_string()),
        }
    }
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct ListRange {
    pub start: RangeBound,
    pub end: RangeBound,
}

impl Display for ListRange {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}..{}", self.start, self.end)
    }
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum RangeBound {
    Index(i64),
    Unbounded,
}

impl Display for RangeBound {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            RangeBound::Index(i) => write!(f, "{i}"),
            RangeBound::Unbounded => write!(f, "..."),
        }
    }
}

impl VariableValue {
    pub fn get<I: Index>(&self, index: I) -> Option<&VariableValue> {
        index.index_into(self)
    }

    pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut VariableValue> {
        index.index_into_mut(self)
    }

    pub fn as_object(&self) -> Option<&BTreeMap<String, VariableValue>> {
        match self {
            VariableValue::Object(map) => Some(map),
            _ => None,
        }
    }

    pub fn as_object_mut(&mut self) -> Option<&mut BTreeMap<String, VariableValue>> {
        match self {
            VariableValue::Object(map) => Some(map),
            _ => None,
        }
    }

    pub fn is_object(&self) -> bool {
        self.as_object().is_some()
    }

    pub fn as_array(&self) -> Option<&Vec<VariableValue>> {
        match self {
            VariableValue::List(list) => Some(list),
            _ => None,
        }
    }

    pub fn as_array_mut(&mut self) -> Option<&mut Vec<VariableValue>> {
        match self {
            VariableValue::List(list) => Some(list),
            _ => None,
        }
    }

    pub fn is_array(&self) -> bool {
        self.as_array().is_some()
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            VariableValue::String(s) => Some(s),
            _ => None,
        }
    }

    pub fn is_string(&self) -> bool {
        self.as_str().is_some()
    }

    pub fn is_number(&self) -> bool {
        matches!(*self, VariableValue::Integer(_) | VariableValue::Float(_))
    }

    pub fn is_i64(&self) -> bool {
        match self {
            VariableValue::Integer(n) => n.is_i64(),
            _ => false,
        }
    }

    pub fn is_f64(&self) -> bool {
        match self {
            VariableValue::Float(n) => n.is_f64(),
            _ => false,
        }
    }

    pub fn is_u64(&self) -> bool {
        match self {
            VariableValue::Integer(n) => n.is_u64(),
            _ => false,
        }
    }

    pub fn as_i64(&self) -> Option<i64> {
        match self {
            VariableValue::Integer(n) => n.as_i64(),
            _ => None,
        }
    }

    pub fn as_f64(&self) -> Option<f64> {
        match self {
            VariableValue::Float(n) => n.as_f64(),
            VariableValue::Integer(n) => n.as_i64().map(|n| n as f64),
            _ => None,
        }
    }

    pub fn as_u64(&self) -> Option<u64> {
        match self {
            VariableValue::Integer(n) => n.as_u64(),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match *self {
            VariableValue::Bool(b) => Some(b),
            _ => None,
        }
    }

    pub fn is_boolean(&self) -> bool {
        self.as_bool().is_some()
    }

    pub fn as_null(&self) -> Option<()> {
        match *self {
            VariableValue::Null => Some(()),
            _ => None,
        }
    }

    pub fn is_null(&self) -> bool {
        self.as_null().is_some()
    }

    pub fn as_date(&self) -> Option<NaiveDate> {
        match *self {
            VariableValue::Date(d) => Some(d),
            _ => None,
        }
    }

    pub fn is_date(&self) -> bool {
        self.as_date().is_some()
    }

    pub fn as_local_time(&self) -> Option<NaiveTime> {
        match *self {
            VariableValue::LocalTime(t) => Some(t),
            _ => None,
        }
    }

    pub fn is_local_time(&self) -> bool {
        self.as_local_time().is_some()
    }

    pub fn as_time(&self) -> Option<ZonedTime> {
        match self {
            VariableValue::ZonedTime(t) => Some(*t),
            _ => None,
        }
    }

    pub fn is_time(&self) -> bool {
        self.as_time().is_some()
    }

    pub fn as_local_date_time(&self) -> Option<NaiveDateTime> {
        match *self {
            VariableValue::LocalDateTime(t) => Some(t),
            _ => None,
        }
    }

    pub fn is_local_date_time(&self) -> bool {
        self.as_local_date_time().is_some()
    }

    pub fn as_zoned_date_time(&self) -> Option<ZonedDateTime> {
        match self {
            VariableValue::ZonedDateTime(t) => Some(t.clone()),
            _ => None,
        }
    }

    pub fn get_date_property(&self, property: String) -> Option<String> {
        if self.is_date() {
            match property.as_str() {
                "year" => Some(match self.as_date() {
                    Some(date) => date.year().to_string(),
                    None => return None,
                }),
                "month" => Some(match self.as_date() {
                    Some(date) => date.month().to_string(),
                    None => return None,
                }),
                "day" => Some(match self.as_date() {
                    Some(date) => date.day().to_string(),
                    None => return None,
                }),
                _ => None,
            }
        } else {
            None
        }
    }

    pub fn is_zoned_date_time(&self) -> bool {
        self.as_zoned_date_time().is_some()
    }

    pub fn as_duration(&self) -> Option<Duration> {
        match self {
            VariableValue::Duration(d) => Some(d.clone()),
            _ => None,
        }
    }

    pub fn is_duration(&self) -> bool {
        self.as_duration().is_some()
    }

    pub fn as_expression(&self) -> Option<AstExpression> {
        match self {
            VariableValue::Expression(e) => Some(e.clone()),
            _ => None,
        }
    }

    pub fn is_expression(&self) -> bool {
        self.as_expression().is_some()
    }

    pub fn as_list_range(&self) -> Option<ListRange> {
        match self {
            VariableValue::ListRange(r) => Some(r.clone()),
            _ => None,
        }
    }

    pub fn is_list_range(&self) -> bool {
        self.as_list_range().is_some()
    }

    pub fn pointer(&self, pointer: &str) -> Option<&VariableValue> {
        if pointer.is_empty() {
            return Some(self);
        }
        if !pointer.starts_with('/') {
            return None;
        }
        pointer
            .split('/')
            .skip(1)
            .map(|x| x.replace("~1", "/").replace("~0", "~"))
            .try_fold(self, |target, token| match target {
                VariableValue::Object(map) => map.get(&token),
                VariableValue::List(list) => parse_index(&token).and_then(|x| list.get(x)),
                _ => None,
            })
    }

    pub fn hash_for_groupby<H: Hasher>(&self, state: &mut H) {
        match self {
            VariableValue::Element(element) => element.get_reference().hash(state),
            _ => self.hash(state),
        }
    }
}

fn parse_index(s: &str) -> Option<usize> {
    if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
        return None;
    }
    s.parse().ok()
}

impl Debug for VariableValue {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        match self {
            VariableValue::Null => formatter.write_str("Null"),
            VariableValue::Bool(boolean) => write!(formatter, "Bool({boolean})"),
            VariableValue::Integer(integer) => write!(formatter, "Integer({integer})"),
            VariableValue::Float(float) => write!(formatter, "Float({float})"),
            VariableValue::String(string) => write!(formatter, "String({string:?})"),
            VariableValue::List(vec) => {
                let _ = formatter.write_str("List ");
                Debug::fmt(vec, formatter)
            }
            VariableValue::Object(map) => {
                let _ = formatter.write_str("Object ");
                Debug::fmt(map, formatter)
            }
            VariableValue::Date(date) => write!(formatter, "Date({date})"),
            VariableValue::LocalTime(time) => write!(formatter, "LocalTime({time})"),
            VariableValue::ZonedTime(time) => write!(formatter, "Time({time})"),
            VariableValue::LocalDateTime(time) => write!(formatter, "LocalDateTime({time})"),
            VariableValue::ZonedDateTime(time) => write!(formatter, "ZonedDateTime({time})"),
            VariableValue::Duration(duration) => write!(formatter, "Duration({duration})"),
            VariableValue::Expression(expression) => {
                write!(formatter, "Expression({expression:?})")
            }
            VariableValue::ListRange(range) => write!(formatter, "ListRange({range:?})"),
            VariableValue::Element(element) => write!(formatter, "Element({element:?})"),
            VariableValue::ElementMetadata(metadata) => {
                write!(formatter, "ElementMetadata({metadata:?})")
            }
            VariableValue::ElementReference(reference) => {
                write!(formatter, "ElementReference({reference:?})")
            }
            VariableValue::Awaiting => write!(formatter, "Awaiting"),
        }
    }
}

impl Display for VariableValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self {
            VariableValue::Null => write!(f, "null"),
            VariableValue::Bool(b) => write!(f, "{b}"),
            VariableValue::Integer(i) => write!(f, "{i}"),
            VariableValue::Float(fl) => write!(f, "{fl}"),
            VariableValue::String(s) => write!(f, "{s}"),
            VariableValue::List(l) => {
                let mut first = true;
                write!(f, "[")?;
                for item in l {
                    if first {
                        first = false;
                    } else {
                        write!(f, ", ")?;
                    }
                    write!(f, "{item}")?;
                }
                write!(f, "]")
            }
            VariableValue::Object(o) => {
                let mut first = true;
                write!(f, "{{")?;
                for (key, value) in o {
                    if first {
                        first = false;
                    } else {
                        write!(f, ", ")?;
                    }
                    write!(f, "{key}: {value}")?;
                }
                write!(f, "}}")
            }
            VariableValue::Date(d) => write!(f, "{d}"),
            VariableValue::LocalTime(t) => write!(f, "{t}"),
            VariableValue::ZonedTime(t) => write!(f, "{t}"),
            VariableValue::LocalDateTime(t) => write!(f, "{t}"),
            VariableValue::ZonedDateTime(t) => write!(f, "{t}"),
            VariableValue::Duration(d) => write!(f, "{d}"),
            VariableValue::Expression(e) => write!(f, "{e:?}"),
            VariableValue::ListRange(r) => write!(f, "{r}"),
            VariableValue::Element(e) => write!(f, "{e:?}"),
            VariableValue::ElementMetadata(m) => write!(f, "{m}"),
            VariableValue::ElementReference(r) => write!(f, "{r}"),
            VariableValue::Awaiting => write!(f, "Awaiting"),
        }
    }
}

pub mod de;
pub mod duration;
pub mod float;
mod from;
mod index;
pub mod integer;
mod partial_eq;
pub mod ser;
#[cfg(test)]
mod tests;
pub mod zoned_datetime;
pub mod zoned_time;