# Copyright 2020 Google LLC
#
# 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
#
#     https://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.
#

from dataclasses import dataclass
from typing import Optional

from rfmt.blocks import LineBlock as LB
from rfmt.blocks import TextBlock as TB
from rfmt.blocks import ChoiceBlock as CB
from rfmt.blocks import WrapBlock as WB

from .utils import with_commas

from .ident import SQLIdentifier

from .query import SQLQuery
from .node import SQLNodeList
from .node import SQLNode
from .const import SQLString
from .types import SQLType
from .expr import SQLExpr


@dataclass(frozen=True)
class SQLFuncExpr(SQLExpr):
    names: SQLNodeList[SQLIdentifier]
    args: SQLNodeList[SQLExpr]

    def sqlf(self, compact):
        name = LB([x.sqlf(True) for x in self.names])
        compact_sql = LB([name, TB('(')] +
                         with_commas(True, self.args) +
                         [TB(')')])

        if compact:
            return compact_sql

        if not self.args:
            return compact_sql

        return CB([
            compact_sql,
            LB([
                LB([name, TB('(')]),
                WB(with_commas(False, self.args)),
                TB(')')
            ])
        ])


@dataclass(frozen=True)
class SQLCustomFuncs(SQLExpr):

    @staticmethod
    def consume(lex) -> 'Optional[SQLCustomFuncs]':
        # TODO(scannell) - add DATE, TIME, DATETIME, TIMESTAMP literals
        return (SQLCAST.consume(lex) or
                SQLDate.consume(lex) or
                SQLCount.consume(lex) or
                SQLExists.consume(lex) or
                SQLInterval.consume(lex) or
                SQLAnalyticNavigation.consume(lex) or
                SQLExtract.consume(lex))


@dataclass(frozen=True)
class SQLExists(SQLCustomFuncs):
    sql: SQLNode

    def sqlf(self, compact):
        return LB([
            TB('EXISTS('),
            self.sql.sqlf(True),
            TB(')'),
        ])

    @staticmethod
    def consume(lex) -> 'Optional[SQLExists]':
        if not lex.consume('EXISTS'):
            return None

        lex.expect('(')
        query = SQLQuery.parse(lex)
        lex.expect(')')

        return SQLExists(query)


@dataclass(frozen=True)
class SQLCount(SQLCustomFuncs):
    isdistinct: bool
    expr: SQLExpr

    def sqlf(self, compact):
        return LB([
            TB('COUNT(' + ('DISTINCT ' if self.isdistinct else '')),
            self.expr.sqlf(compact),
            TB(')'),
        ])

    @staticmethod
    def consume(lex) -> 'Optional[SQLCount]':
        if not lex.consume('COUNT'):
            return None
        lex.expect('(')