<?php

namespace TdyGames\Controller\Rest\Contests;

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

class SlotsController extends BaseRestController
{
    protected $identifierName = 'st';

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

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

        $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->getContestsSlotsTable()->setIndent(self::LOGGER_INDENT)->fetch($cn, $q, $x, $f, $s, $isPaginated);
        $resultSet->setCurrentPageNumber((int) $p);
        $resultSet->setItemCountPerPage($l);

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

        $slots = iterator_to_array($resultSet, false);

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

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

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

        ]);
    }

    /**
     * @param int|string $id
     *
     * @return JsonModel
     */
    public function get($id)
    {
        $contest = $this->getContestsSlotsTable()->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();
        }
    }

}
