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
/*
 * 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};

use itertools::Itertools;

use crate::{
    common::{
        error::{collect_err, TypeQLError},
        token,
        validatable::Validatable,
        Result,
    },
    pattern::{Conjunction, VariablesRetrieved},
    query::{
        modifier::{Modifiers, Sorting},
        AggregateQueryBuilder, MatchClause, TypeQLGetGroup,
    },
    variable::{variable::VariableRef, Variable},
    write_joined,
};

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TypeQLGet {
    pub match_clause: MatchClause,
    pub filter: Filter,
    pub modifiers: Modifiers,
}

impl AggregateQueryBuilder for TypeQLGet {}

impl TypeQLGet {
    pub fn new(match_clause: MatchClause) -> Self {
        TypeQLGet { match_clause, filter: Filter::default(), modifiers: Modifiers::default() }
    }

    pub fn sort(self, sorting: impl Into<Sorting>) -> Self {
        TypeQLGet { modifiers: self.modifiers.sort(sorting), ..self }
    }

    pub fn limit(self, limit: usize) -> Self {
        TypeQLGet { modifiers: self.modifiers.limit(limit), ..self }
    }

    pub fn offset(self, offset: usize) -> Self {
        TypeQLGet { modifiers: self.modifiers.offset(offset), ..self }
    }

    pub fn group(self, var: impl Into<Variable>) -> TypeQLGetGroup {
        TypeQLGetGroup { query: self, group_var: var.into() }
    }
}

impl Validatable for TypeQLGet {
    fn validate(&self) -> Result {
        let match_variables = self.match_clause.retrieved_variables().collect();
        let filter_vars = HashSet::from_iter((&self.filter.vars).iter().map(Variable::as_ref));
        let retrieved_variables = if self.filter.vars.is_empty() { &match_variables } else { &filter_vars };
        collect_err([
            self.match_clause.validate(),
            validate_filters_are_in_scope(&match_variables, &self.filter),
            self.modifiers.sorting.as_ref().map(|s| s.validate(&retrieved_variables)).unwrap_or(Ok(())),
            validate_variable_names_are_unique(&self.match_clause.conjunction),
        ])
    }
}

impl VariablesRetrieved for TypeQLGet {
    fn retrieved_variables(&self) -> Box<dyn Iterator<Item = VariableRef<'_>> + '_> {
        if !self.filter.vars.is_empty() {
            Box::new(self.filter.vars.iter().map(|v| v.as_ref()))
        } else {
            self.match_clause.retrieved_variables()
        }
    }
}

fn validate_filters_are_in_scope(match_variables: &HashSet<VariableRef<'_>>, filter: &Filter) -> Result {
    let mut seen = HashSet::new();
    collect_err(filter.vars.iter().map(|r| {
        if !r.is_name() {
            Err(TypeQLError::VariableNotNamed().into())
        } else if !match_variables.contains(&r.as_ref()) {
            Err(TypeQLError::GetVarNotBound(r.to_owned()).into())
        } else if seen.contains(&r) {
            Err(TypeQLError::GetVarRepeating(r.to_owned()).into())
        } else {
            seen.insert(r);
            Ok(())
        }
    }))
}

fn validate_variable_names_are_unique(conjunction: &Conjunction) -> Result {
    let all_refs = conjunction.variables_recursive();
    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 fmt::Display for TypeQLGet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.match_clause)?;
        write!(f, "\n{}", self.filter)?;
        if !self.modifiers.is_empty() {
            write!(f, "\n{}", self.modifiers)
        } else {
            Ok(())
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct Filter {
    pub vars: Vec<Variable>,
}

impl fmt::Display for Filter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", token::Clause::Get)?;
        if !self.vars.is_empty() {
            write!(f, " ")?;
            write_joined!(f, ", ", self.vars)?;
        }
        write!(f, ";")
    }
}