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
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃ This file is part of the Perspective library, distributed under the terms ┃
// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

use std::fmt::Display;
use std::str::FromStr;

use itertools::Itertools;
use serde::{Deserialize, Serialize};
use ts_rs::TS;

use crate::proto;
use crate::proto::scalar;

#[derive(Clone, Deserialize, Debug, PartialEq, Serialize, TS)]
#[serde(untagged)]
pub enum Scalar {
    Float(f64),
    String(String),
    Bool(bool),
    DateTime(f64),
    Null,
    // // Can only have one u64 representation ...
    // Date(u64)
    // Int(u32)
}

impl Default for Scalar {
    fn default() -> Self {
        Self::Null
    }
}

impl Display for Scalar {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Self::Float(x) => write!(fmt, "{}", x),
            Self::String(x) => write!(fmt, "{}", x),
            Self::Bool(x) => write!(fmt, "{}", x),
            Self::DateTime(x) => write!(fmt, "{}", x),
            Self::Null => write!(fmt, ""),
        }
    }
}

#[allow(clippy::upper_case_acronyms)]
#[derive(Clone, Copy, Deserialize, Debug, Eq, PartialEq, Serialize, TS)]
#[serde()]
pub enum FilterOp {
    #[serde(rename = "contains")]
    Contains,

    #[serde(rename = "not in")]
    NotIn,

    #[serde(rename = "in")]
    In,

    #[serde(rename = "begins with")]
    BeginsWith,

    #[serde(rename = "ends with")]
    EndsWith,

    #[serde(rename = "is null")]
    IsNull,

    #[serde(rename = "is not null")]
    IsNotNull,

    #[serde(rename = ">")]
    GT,

    #[serde(rename = "<")]
    LT,

    #[serde(rename = "==")]
    EQ,

    #[serde(rename = ">=")]
    GTE,

    #[serde(rename = "<=")]
    LTE,

    #[serde(rename = "!=")]
    NE,
}

impl From<FilterOp> for proto::FilterOp {
    fn from(value: FilterOp) -> Self {
        match value {
            FilterOp::Contains => proto::FilterOp::FilterContains,
            FilterOp::NotIn => proto::FilterOp::FilterNotIn,
            FilterOp::In => proto::FilterOp::FilterIn,
            FilterOp::BeginsWith => proto::FilterOp::FilterBeginsWith,
            FilterOp::EndsWith => proto::FilterOp::FilterEndsWith,
            FilterOp::IsNull => proto::FilterOp::FilterIsNull,
            FilterOp::IsNotNull => proto::FilterOp::FilterIsNotNull,
            FilterOp::GT => proto::FilterOp::FilterGt,
            FilterOp::LT => proto::FilterOp::FilterLt,
            FilterOp::EQ => proto::FilterOp::FilterEq,
            FilterOp::GTE => proto::FilterOp::FilterGteq,
            FilterOp::LTE => proto::FilterOp::FilterLteq,
            FilterOp::NE => proto::FilterOp::FilterNe,
        }
    }
}

impl From<proto::FilterOp> for FilterOp {
    fn from(value: proto::FilterOp) -> Self {
        match value {
            proto::FilterOp::FilterContains => FilterOp::Contains,
            proto::FilterOp::FilterNotIn => FilterOp::NotIn,
            proto::FilterOp::FilterIn => FilterOp::In,
            proto::FilterOp::FilterBeginsWith => FilterOp::BeginsWith,
            proto::FilterOp::FilterEndsWith => FilterOp::EndsWith,
            proto::FilterOp::FilterIsNull => FilterOp::IsNull,
            proto::FilterOp::FilterIsNotNull => FilterOp::IsNotNull,
            proto::FilterOp::FilterGt => FilterOp::GT,
            proto::FilterOp::FilterLt => FilterOp::LT,
            proto::FilterOp::FilterEq => FilterOp::EQ,
            proto::FilterOp::FilterGteq => FilterOp::GTE,
            proto::FilterOp::FilterLteq => FilterOp::LTE,
            proto::FilterOp::FilterNe => FilterOp::NE,
            proto::FilterOp::FilterUnknown => todo!(),
            proto::FilterOp::FilterAnd => todo!(),
            proto::FilterOp::FilterOr => todo!(),
        }
    }
}

impl Display for FilterOp {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        let op = match self {
            Self::Contains => "contains",
            Self::In => "in",
            Self::NotIn => "not in",
            Self::BeginsWith => "begins with",
            Self::EndsWith => "ends with",
            Self::IsNull => "is null",
            Self::IsNotNull => "is not null",
            Self::GT => ">",
            Self::LT => "<",
            Self::EQ => "==",
            Self::GTE => ">=",
            Self::LTE => "<=",
            Self::NE => "!=",
        };

        write!(fmt, "{}", op)
    }
}

impl FromStr for FilterOp {
    type Err = String;

    fn from_str(input: &str) -> std::result::Result<Self, <Self as std::str::FromStr>::Err> {
        match input {
            "contains" => Ok(Self::Contains),
            "in" => Ok(Self::In),
            "not in" => Ok(Self::NotIn),
            "begins with" => Ok(Self::BeginsWith),
            "ends with" => Ok(Self::EndsWith),
            "is null" => Ok(Self::IsNull),
            "is not null" => Ok(Self::IsNotNull),
            ">" => Ok(Self::GT),
            "<" => Ok(Self::LT),
            "==" => Ok(Self::EQ),
            ">=" => Ok(Self::GTE),
            "<=" => Ok(Self::LTE),
            "!=" => Ok(Self::NE),
            x => Err(format!("Unknown filter operator {}", x)),
        }
    }
}

#[derive(Clone, Deserialize, Debug, PartialEq, Serialize, TS)]
#[serde(untagged)]
pub enum FilterTerm {
    Array(Vec<Scalar>),
    Scalar(#[serde(default)] Scalar),
}

impl Default for FilterTerm {
    fn default() -> Self {
        Self::Scalar(Scalar::Null)
    }
}

impl Display for FilterTerm {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Self::Scalar(x) => {
                write!(fmt, "{}", x)?;
            },
            Self::Array(xs) => write!(
                fmt,
                "{}",
                Itertools::intersperse(xs.iter().map(|x| format!("{}", x)), ",".to_owned())
                    .collect::<String>()
            )?,
        }

        Ok(())
    }
}

#[derive(Clone, Deserialize, Debug, PartialEq, Serialize, TS)]
#[serde()]
pub struct Filter(pub String, pub FilterOp, #[serde(default)] pub FilterTerm);

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, TS)]
pub enum FilterReducer {
    #[serde(rename = "and")]
    And,
    #[serde(rename = "or")]
    Or,
}

impl Default for FilterReducer {
    fn default() -> Self {
        Self::And
    }
}

impl From<Scalar> for proto::Scalar {
    fn from(value: Scalar) -> Self {
        match value {
            Scalar::Float(x) => proto::Scalar {
                scalar: Some(scalar::Scalar::Float(x)),
            },
            Scalar::String(x) => proto::Scalar {
                scalar: Some(scalar::Scalar::String(x)),
            },
            Scalar::Bool(x) => proto::Scalar {
                scalar: Some(scalar::Scalar::Bool(x)),
            },
            // Scalar::Date(_) => todo!(),
            Scalar::DateTime(x) => proto::Scalar {
                scalar: Some(scalar::Scalar::Datetime(x as i64)),
            },
            Scalar::Null => proto::Scalar {
                scalar: Some(scalar::Scalar::Null(0)),
            },
        }
    }
}

impl From<proto::Scalar> for Scalar {
    fn from(value: proto::Scalar) -> Self {
        match value.scalar {
            Some(scalar::Scalar::Bool(x)) => Scalar::Bool(x),
            Some(scalar::Scalar::String(x)) => Scalar::String(x),
            Some(scalar::Scalar::Int(x)) => Scalar::Float(x as f64),
            Some(scalar::Scalar::Date(x)) => Scalar::DateTime(x as f64),
            Some(scalar::Scalar::Float(x)) => Scalar::Float(x),
            Some(scalar::Scalar::Datetime(x)) => Scalar::DateTime(x as f64),
            Some(scalar::Scalar::Null(_)) => Scalar::Null,
            None => Scalar::Null,
        }
    }
}

impl From<Filter> for proto::Filter {
    fn from(value: Filter) -> Self {
        proto::Filter {
            column: value.0,
            op: proto::FilterOp::from(value.1) as i32,
            value: match value.2 {
                FilterTerm::Scalar(x) => vec![x.into()],
                FilterTerm::Array(x) => x.into_iter().map(|x| x.into()).collect(),
            },
        }
    }
}

impl From<proto::Filter> for Filter {
    fn from(value: proto::Filter) -> Self {
        Filter(
            value.column,
            FilterOp::from(proto::FilterOp::try_from(value.op).unwrap()),
            if value.value.len() == 1 {
                FilterTerm::Scalar(value.value.into_iter().next().unwrap().into())
            } else {
                FilterTerm::Array(value.value.into_iter().map(|x| x.into()).collect())
            },
        )
    }
}