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
/*
 * Copyright (C) 2022 Vaticle
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 std::{collections::HashSet, fmt, iter};

use itertools::Itertools;

use crate::{
    common::{
        error::{collect_err, TypeQLError},
        string::indent,
        token,
        validatable::Validatable,
        Result,
    },
    pattern::{Label, VariablesRetrieved},
    query::{modifier::Modifiers, MatchClause, TypeQLGetAggregate},
    variable::{variable, variable::VariableRef, Variable},
    write_joined,
};

#[derive(Debug, Eq, PartialEq)]
pub struct TypeQLFetch {
    pub match_clause: MatchClause,
    pub projections: Vec<Projection>,
    pub modifiers: Modifiers,
}

impl TypeQLFetch {
    fn validate_names_are_unique(&self) -> Result {
        let all_refs = self
            .match_clause
            .retrieved_variables()
            .chain(self.projections.iter().flat_map(|p| p.key_variable().into_iter().chain(p.value_variables())));
        let (concept_refs, value_refs): (HashSet<VariableRef<'_>>, HashSet<VariableRef<'_>>) =
            all_refs.partition(|r| r.is_concept());
        let concept_names = concept_refs.iter().map(|r| r).collect::<HashSet<_>>();
        let value_names = value_refs.iter().map(|r| r).collect::<HashSet<_>>();
        let common_refs = concept_names.intersection(&value_names).collect::<HashSet<_>>();
        if !common_refs.is_empty() {
            return Err(TypeQLError::VariableNameConflict(common_refs.iter().map(|r| r.to_string()).join(", ")).into());
        }
        Ok(())
    }
}

impl Validatable for TypeQLFetch {
    fn validate(&self) -> Result {
        let match_variables = self.match_clause.retrieved_variables().collect();
        collect_err([
            self.match_clause.validate(),
            self.modifiers.sorting.as_ref().map(|s| s.validate(&match_variables)).unwrap_or(Ok(())),
            self.validate_names_are_unique(),
        ])
    }
}

impl VariablesRetrieved for TypeQLFetch {
    fn retrieved_variables(&self) -> Box<dyn Iterator<Item = VariableRef<'_>> + '_> {
        Box::new(
            self.match_clause.retrieved_variables().chain(self.projections.iter().flat_map(Projection::key_variable)),
        )
    }
}

#[derive(Debug, Eq, PartialEq)]
pub enum Projection {
    Variable(ProjectionKeyVar),
    Attribute(ProjectionKeyVar, Vec<ProjectionAttribute>),
    Subquery(ProjectionKeyLabel, ProjectionSubquery),
}

impl Projection {
    pub fn key_variable(&self) -> Option<VariableRef<'_>> {
        match self {
            Projection::Variable(key) => Some(key.variable.as_ref()),
            Projection::Attribute(key, _) => Some(key.variable.as_ref()),
            Projection::Subquery(_, _) => None,
        }
    }

    pub fn value_variables(&self) -> Box<dyn Iterator<Item = VariableRef<'_>> + '_> {
        match self {
            Projection::Variable(_) => Box::new(iter::empty()),
            Projection::Attribute(_, _) => Box::new(iter::empty()),
            Projection::Subquery(_, subquery) => subquery.variables(),
        }
    }
}

#[derive(Debug, Eq, PartialEq)]
pub struct ProjectionKeyVar {
    pub(crate) variable: Variable,
    pub(crate) label: Option<ProjectionKeyLabel>,
}

impl ProjectionKeyVar {
    pub fn label(self, label: impl Into<ProjectionKeyLabel>) -> Self {
        ProjectionKeyVar { label: Some(label.into()), ..self }
    }
}

impl<T: Into<ProjectionKeyVar>> From<T> for Projection {
    fn from(key_var: T) -> Self {
        Projection::Variable(key_var.into())
    }
}

pub trait ProjectionKeyVarBuilder {
    fn label(self, label: impl Into<ProjectionKeyLabel>) -> ProjectionKeyVar;
}

impl<T: Into<Variable>> ProjectionKeyVarBuilder for T {
    fn label(self, label: impl Into<ProjectionKeyLabel>) -> ProjectionKeyVar {
        let labeled = label.into();
        ProjectionKeyVar { variable: self.into(), label: Some(labeled) }
    }
}

impl<T: Into<Variable>, U: Into<ProjectionKeyLabel>> From<(T, U)> for ProjectionKeyVar {
    fn from((var, label): (T, U)) -> Self {
        ProjectionKeyVar { variable: var.into(), label: Some(label.into()) }
    }
}

impl<T: Into<Variable>> From<T> for ProjectionKeyVar {
    fn from(var: T) -> Self {
        ProjectionKeyVar { variable: var.into(), label: None }
    }
}

#[derive(Debug, Eq, PartialEq)]
pub enum ProjectionKeyLabel {
    Quoted(String),
    Unquoted(String),
}

impl ProjectionKeyLabel {
    pub fn map_subquery_get_aggregate(self, subquery: TypeQLGetAggregate) -> Projection {
        Projection::Subquery(self.into(), ProjectionSubquery::GetAggregate(subquery))
    }

    pub fn map_subquery_fetch(self, subquery: TypeQLFetch) -> Projection {
        Projection::Subquery(self.into(), ProjectionSubquery::Fetch(Box::new(subquery)))
    }

    fn must_quote(s: &str) -> bool {
        // TODO: we should actually check against valid label regex, instead of valid variable regex - Java has to be updated too
        let x = !variable::is_valid_variable_name(s);
        x
    }
}

impl From<&str> for ProjectionKeyLabel {
    fn from(value: &str) -> Self {
        Self::from(value.to_owned())
    }
}

impl From<String> for ProjectionKeyLabel {
    fn from(label: String) -> Self {
        if Self::must_quote(label.as_ref()) {
            ProjectionKeyLabel::Quoted(label)
        } else {
            ProjectionKeyLabel::Unquoted(label)
        }
    }
}

#[derive(Debug, Eq, PartialEq)]
pub struct ProjectionAttribute {
    pub(crate) attribute: Label,
    pub(crate) label: Option<ProjectionKeyLabel>,
}

impl ProjectionAttribute {
    pub fn label(self, label: impl Into<ProjectionKeyLabel>) -> Self {
        ProjectionAttribute { label: Some(label.into()), ..self }
    }
}

impl From<&str> for ProjectionAttribute {
    fn from(attribute: &str) -> Self {
        Self::from(attribute.to_owned())
    }
}

impl From<String> for ProjectionAttribute {
    fn from(attribute: String) -> Self {
        ProjectionAttribute { attribute: Label::from(attribute), label: None }
    }
}

impl From<(&str, &str)> for ProjectionAttribute {
    fn from((attribute, label): (&str, &str)) -> Self {
        Self::from((attribute.to_owned(), label.to_owned()))
    }
}

impl From<(String, String)> for ProjectionAttribute {
    fn from((attribute, label): (String, String)) -> Self {
        ProjectionAttribute { attribute: Label::from(attribute), label: Some(label.into()) }
    }
}

#[derive(Debug, Eq, PartialEq)]
pub enum ProjectionSubquery {
    GetAggregate(TypeQLGetAggregate),
    Fetch(Box<TypeQLFetch>),
}

impl ProjectionSubquery {
    pub fn variables(&self) -> Box<dyn Iterator<Item = VariableRef<'_>> + '_> {
        match self {
            ProjectionSubquery::GetAggregate(query) => query.query.retrieved_variables(),
            ProjectionSubquery::Fetch(query) => query.retrieved_variables(),
        }
    }
}

pub trait ProjectionBuilder {
    fn map_attribute(self, attribute: impl Into<ProjectionAttribute>) -> Projection;
    fn map_attributes(self, attribute: Vec<ProjectionAttribute>) -> Projection;
}

impl<T: Into<ProjectionKeyVar>> ProjectionBuilder for T {
    fn map_attribute(self, attribute: impl Into<ProjectionAttribute>) -> Projection {
        Projection::Attribute(self.into(), vec![attribute.into()])
    }

    fn map_attributes(self, attributes: Vec<ProjectionAttribute>) -> Projection {
        Projection::Attribute(self.into(), attributes)
    }
}
impl fmt::Display for TypeQLFetch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "{}", self.match_clause)?;
        writeln!(f, "{}", token::Clause::Fetch)?;
        write_joined!(f, "\n", self.projections)?;
        if !self.modifiers.is_empty() {
            write!(f, "\n{}", self.modifiers)
        } else {
            Ok(())
        }
    }
}

impl fmt::Display for Projection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Projection::Variable(key) => {
                write!(f, "{};", key)
            }
            Projection::Attribute(key, attrs) => {
                write!(f, "{}: ", key)?;
                write_joined!(f, ", ", attrs)?;
                write!(f, ";")
            }
            Projection::Subquery(label, subquery) => {
                write!(f, "{}: {{\n{}\n}};", label, indent(subquery.to_string().as_ref()))
            }
        }
    }
}

impl fmt::Display for ProjectionKeyVar {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.variable)?;
        if let Some(label) = &self.label {
            write!(f, " {} {}", token::Projection::As, label)
        } else {
            Ok(())
        }
    }
}

impl fmt::Display for ProjectionKeyLabel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProjectionKeyLabel::Quoted(s) => write!(f, "\"{}\"", s),
            ProjectionKeyLabel::Unquoted(s) => write!(f, "{}", s),
        }
    }
}

impl fmt::Display for ProjectionAttribute {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.attribute)?;
        if let Some(label) = &self.label {
            write!(f, " {} {}", token::Projection::As, label)
        } else {
            Ok(())
        }
    }
}

impl fmt::Display for ProjectionSubquery {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProjectionSubquery::GetAggregate(query) => {
                write!(f, "{}", query)
            }
            ProjectionSubquery::Fetch(query) => {
                write!(f, "{}", query)
            }
        }
    }
}