<?php
declare(strict_types=1);

namespace FCA\StockApi\Collection\Sort;

use FCA\StockApi\Collection\Filter\Builder\Validator;
use FCA\StockApi\Exception\ApiException;

class Sort
{
    const DESC = -1;
    const ASC = 1;

    /**
     * @var array
     */
    private $sort = [];

    public function addSortBy(string $field, int $order): self
    {
        if (!Validator::isValidField($field)) {
            throw new ApiException('Field: "' . $field . '" is invalid!');
        }

        if ($order !== Sort::ASC and $order !== Sort::DESC) {
            throw new ApiException('Order: "' . $order . '" is invalid!');
        }

        if ($this->sort === ['random' => true]) {
            throw new ApiException('Cannot set sorting when random sort is set!');
        }

        $this->sort[$field] = $order;

        return $this;
    }

    public function setRandom(): void
    {
        if ($this->sort !== [] and $this->sort !== ['random' => true]) {
            throw new ApiException('Cannot set random sorting when other sort is set!');
        }

        $this->sort = ['random' => true];
    }

    public function clearSort(): self
    {
        $this->sort = [];

        return $this;
    }

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