<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsJdisc\Controller\Table;

use Idoit\Dto\Serialization\Serializer;
use Throwable;

class SearchParams
{
    public function __construct(
        protected int $page = 0,
        protected int $perPage = 100,
        protected ?Sort $sort = null,
        protected ?string $searchTerm = '',
    )
    {
    }

    public function getPage(): int
    {
        return $this->page;
    }

    public function getOffset(): int
    {
        return max(0, $this->page - 1) * $this->perPage;
    }

    public function getPerPage(): int
    {
        return $this->perPage;
    }

    public function getSort(): ?Sort
    {
        return $this->sort;
    }

    public function getSearchTerm(): ?string
    {
        return $this->searchTerm;
    }

    public static function fromParams(?string $params): SearchParams
    {
        $result = new SearchParams();
        try {
            $result = Serializer::fromJson(SearchParams::class, json_decode($params, true));
        } catch (Throwable) {
            // fallback
        }
        return $result;
    }
}
