<?php

declare(strict_types=1);

namespace apexl\Io\modules\tabulator\Request;

use apexl\Io\modules\tabulator\Collections\TabulatorFilterCollection;
use apexl\Io\modules\tabulator\Collections\TabulatorSortCollection;
use apexl\Io\Request\IoRequest;

final class TabulatorRequest extends IoRequest
{
    private const string QUERY__SIZE = 'size';
    private const string QUERY__PAGE = 'page';
    private const string QUERY__FILTERS = 'filter';
    private const string QUERY__SORT = 'sort';
    private const string QUERY__SUB_ENTITY_KEY = 'subEntityKey';

    public function size(): int
    {
        return (int) $this->query(self::QUERY__SIZE, 20);
    }

    public function page(): int
    {
        return (int) $this->query(self::QUERY__PAGE, 1);
    }

    public function sort(): TabulatorSortCollection
    {
        if ($sort = $this->query(self::QUERY__SORT)) {
            $sort = json_decode($sort, true);

            return TabulatorSortCollection::fromTabulatorArray($sort);
        }

        return new TabulatorSortCollection();
    }

    public function filters(): TabulatorFilterCollection
    {
        $filters = $this->query(self::QUERY__FILTERS);
        $filters = $filters ? json_decode($filters, true) : [];

        return TabulatorFilterCollection::createFromArray($filters);
    }

    public function subEntityKey(): string
    {
        return (string) $this->query(self::QUERY__SUB_ENTITY_KEY, '');
    }
}
