<?php

namespace apexl\Io\modules\tabulator\Dto;

use apexl\dto\Dto;
use apexl\Io\dto\LoaderSort;
use apexl\Io\includes\System;
use apexl\Io\modules\tabulator\Interfaces\HasTabulatorViewInterface;
use apexl\Io\modules\tabulator\Services\TabulatorFieldRenamer;
use apexl\Vault\enums\SortDirection;

final readonly class TabulatorSort extends Dto
{
    public function __construct(
        public string $field,
        public SortDirection $direction,
    ) {}

    /**
     * @param $sort array{'field': string, 'dir': SortDirection}
     */
    public static function fromTabulatorArray(array $sort): TabulatorSort
    {
        return new TabulatorSort(
            field: $sort['field'],
            direction: SortDirection::get($sort['dir']),
        );
    }

    public function toLoaderSort(HasTabulatorViewInterface $entity): LoaderSort
    {
        $renamer = System::getRegisteredService(TabulatorFieldRenamer::class);
        $field = $renamer->rename($column?->sortOn ?? $this->field);

        $column = $entity->tabulatable()->column($this->field);

        if ($column?->sortQueryCallback) {
            return ($column->sortQueryCallback)($field, $this->direction);
        }

        return new LoaderSort(
            field: $field,
            direction: $this->direction,
        );
    }

    public function forTabulator(): array
    {
        return [
            'column' => $this->field,
            'dir' => $this->direction->name,
        ];
    }


}
