<?php

namespace TdyGames\Controller\Rest\Contests\Players;

use TdyCommons\Controller\BaseRestController;
use TdyGames\Model\Mixture;
use Zend\View\Model\JsonModel;

class MixturesController extends BaseRestController
{
    protected $identifierName = 'mx';

    /**
     * @return JsonModel
     */
    public function getList()
    {
        $this->getLogger()->debug('Contests\Mixtures\MixturesControllers::getList() start.');

        $cn = $this->params()->fromRoute('id', null);
        $pl = $this->params()->fromRoute('pl', null);

        $q = $this->params()->fromQuery('q', '');
        $p = (int) $this->params()->fromQuery('p', 1);
        $l = (int) $this->params()->fromQuery('l', $this->getSettingsTable()->get('items-per-page'));
        $s = $this->params()->fromQuery('s', []);
        $f = $this->params()->fromQuery('f', []);
        $x = [];

        $isPaginated = $l > 0;

        $resultSet = $this->getContestsMixturesTable()->setIndent(self::LOGGER_INDENT)->fetch($cn, $pl, null, $q, $x, $f, $s, $isPaginated);

        if ($isPaginated) {
            $resultSet->setCurrentPageNumber((int) $p);
            $resultSet->setItemCountPerPage($l);
        }

        if ($p > 0) {
            $i = (($p - 1) * $l);
        } else {
            $i = 0;
        }

        $mixtures = iterator_to_array($resultSet, false);

        /**
         * @var int     $k
         * @var Mixture $mixture
         */
        foreach ($mixtures as $k => $mixture) {
            $mixture->setServiceLocator($this->getServiceLocator());
            $mixtures[$k]->row = ++$i;
            $mixtures[$k]      = $mixture->toStdClass();
        }

        $this->getLogger()->debug('Contests\Mixtures\MixturesController::getList() end.');

        return $this->statusOk([
            'entries'    => $mixtures,
            'pagination' => [
                'pageNumber' => $p,
                'pageSize'   => $l,
                'totalItems' => $isPaginated ? $resultSet->getTotalItemCount() : count($mixtures),
                'totalPages' => $isPaginated ? $resultSet->count() : 1,
            ],

        ]);
    }

    /**
     * @param int|string $id
     *
     * @return JsonModel
     */
    public function get($id)
    {
        $contest = $this->getContestsMixturesTable()->get($id);

        if ($contest) {
            $contest->setServiceLocator($this->getServiceLocator());

            return $this->statusOk([
                'entry'      => $contest->toStdClass(),
                'pagination' => [
                    'pageNumber' => 1,
                    'pageSize'   => 1,
                    'totalItems' => 1,
                    'totalPages' => 1,
                ],
            ]);
        } else {
            return $this->statusNotFound();
        }
    }

}
