<?php

declare(strict_types=1);

namespace apexl\Io\modules\tabulator\Collections;

use apexl\Io\collections\LoaderSortCollection;
use apexl\Io\dto\LoaderSort;
use apexl\Io\modules\tabulator\Dto\TabulatorSort;
use apexl\Io\modules\tabulator\Interfaces\HasTabulatorViewInterface;
use Arrayy\Arrayy;
use Arrayy\Collection\AbstractCollection;

/** @extends AbstractCollection<TabulatorSort> */
class TabulatorSortCollection extends AbstractCollection
{

    public static function fromTabulatorArray(array $sorts): TabulatorSortCollection
    {
        return TabulatorSortCollection::createFromObject(
            Arrayy::create($sorts)->map(
                fn(array $sort): TabulatorSort => TabulatorSort::fromTabulatorArray($sort)
            )
        );
    }

    public function getType(): string
    {
        return TabulatorSort::class;
    }

    public function toLoaderSortCollection(HasTabulatorViewInterface $entity): LoaderSortCollection
    {
        $sort = $this;
        if ($this->isEmpty()) {
            $sort = $entity->tabulatable()->sort();
        }

        return LoaderSortCollection::createFromObject(
            $sort->mergeAppendNewIndex($entity->tabulatable()->immutableSorts()->toArray())->map(
                fn(TabulatorSort $sort): LoaderSort => $sort->toLoaderSort($entity)
            )
        );

    }

    public function forTabulator(): TabulatorSortCollection
    {
        return $this->map(
            fn(TabulatorSort $sort): array => $sort->forTabulator()
        );
    }
}
