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

from entity_read.sql.atoms import Selectable

from entity_read import sql
from entity_read.entity import Entity
from .expression import Expression
from .query_token import QueryToken


@dataclass(frozen=True, kw_only=True, repr=False)
class Order(QueryToken):
    body: Expression
    asc: bool = True
    nulls_last: bool | None = None

    def eval(self, entity_type: type[Entity], variables: dict[str, Selectable]) -> sql.atoms.order.Order:
        return sql.atoms.order.Order(
            value=self.body.eval(entity_type, variables), asc=self.asc, nulls_last=self.nulls_last)

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