<?php

namespace TdyGames\Controller\Rest\Contests\Slots;

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.');

        $st = $this->params()->fromRoute('st', 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(null, null, $st, $q, $x, $f, $s, $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' => $resultSet->getTotalItemCount(),
                'totalPages' => $resultSet->count(),
            ],

        ]);
    }

    /**
     * @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();
        }
    }

}
