#  Copyright (C) 2023
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Mike Orlov <m.orlov@abm-jsc.ru>
import typing
from dataclasses import dataclass

from entity_read.sql.context import SqlContext
# from entity_read.select.atoms.atoms import NodeType
from .node import Node, SQL
from entity_read.sql.atoms.abstract import Selectable
from entity_read.sql.atoms.column import Column


@dataclass(kw_only=True, frozen=True, slots=True)
class Order(Node):
    def to_sql(self, context: SqlContext, key_to_expression=None) -> SQL:
        pass

    # type = NodeType.order
    value: Selectable
    asc: bool = True
    nulls_last: typing.Optional[bool] = None

    def to_order_sql(self, context, key_to_expression: dict = None) -> str:
        expression_str = self.value.to_sql(context, key_to_expression)
        if not self.asc:
            expression_str += " DESC"
        if self.nulls_last is not None:
            expression_str += " NULLS " + ("LAST" if self.nulls_last else "FIRST")
        return expression_str

    def requires(self) -> list[Column]:
        return self.value.requires()

    def get_name(self) -> str:
        nulls_last = f",nulls_last={self.nulls_last}" if self.nulls_last is not None else ''
        return f"order({self.value.get_name()},asc={self.asc}{nulls_last})"
