<?php

namespace TdyAvatars\Controller\Rest;

use TdyAvatars\Model\Avatar;
use TdyCommons\Controller\BaseRestController;
use Zend\View\Model\JsonModel;

class AvatarsController extends BaseRestController
{
    protected $identifierName = 'id';

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

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

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

        $avatars = iterator_to_array($resultSet, false);

        /**
         * @var int     $k
         * @var Avatar $avatar
         */
        foreach ($avatars as $k => $avatar) {
            $avatar->setServiceLocator($this->getServiceLocator());
            $avatars[$k]->row      = ++$i;
            $avatars[$k]->playerId = $this->getCurrentPlayer()->id;
            $avatars[$k]           = $avatar->toStdClass();
        }

        $this->getLogger()->debug('AvatarsController::getList() end.');

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

        ]);
    }

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

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

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

}
