<?php

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 = [];

    /**
     * @param $field
     * @param $order
     * @return $this
     * @throws ApiException
     */
    public function addSortBy($field, $order)
    {
        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;
    }

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

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

    /**
     * @return $this
     */
    public function clearSort()
    {
        $this->sort = [];

        return $this;
    }

    /**
     * @return array
     */
    public function getSort()
    {
        return $this->sort;
    }
}
