<?php

namespace TdyPlayers\Controller\Rest;

use TdyPlayers\Model\Player;
use TdyPlayers\InputFilter\Player as PlayerInputFilter;
use TdyCommons\Controller\BaseRestController;
use Zend\View\Model\JsonModel;

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

    /**
     * @return JsonModel
     */
    public function getList()
    {
        $this->getLogger()->debug('PlayersController::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 = [];

        $resultSet = $this->getPlayersTable()->setIndent(self::LOGGER_INDENT)
            ->fetch($q, $x, $f, $s, true);
        $resultSet->setCurrentPageNumber((int) $p);
        $resultSet->setItemCountPerPage($l);

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

        $players = iterator_to_array($resultSet, false);

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

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

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

        ]);
    }

    /**
     * @param int|string $usr
     *
     * @return JsonModel
     */
    public function get($usr)
    {
        $player = $this->getPlayersTable()->get($usr);

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

    /**
     * @param mixed $data
     *
     * @return JsonModel
     */
    public function create($data)
    {
        $this->getLogger()->debug('PlayersController::create() start.');

        $data['id'] = 0;

        $inputFilter = new PlayerInputFilter($this->getServiceLocator());
        $inputFilter->setData($data);

        if ($inputFilter->isValid()) {
            $this->getLogger()->debug(self::LOGGER_INDENT . 'Input Filter is valid. Continue.');

            $data = $inputFilter->getValues();

            $player            = new Player($data);
            $player->createdBy = $this->getCurrentPlayer()->id;

            $player = $this->getPlayersTable()->setIndent(self::LOGGER_INDENT)->save($player);

            $this->getLogger()->debug('PlayersController::create() end.');

            return $this->statusOk([
                'entry'      => $player->toStdClass(),
                'pagination' => [
                    'pageNumber' => 1,
                    'pageSize'   => 1,
                    'totalItems' => 1,
                    'totalPages' => 1,
                ],
            ]);
        } else {
            $this->getLogger()->debug('PlayersController::create() end.');

            return $this->statusBadRequest([
                'system'    => [
                    'id'          => 4001,
                    'description' => 'Invalid Request'
                ],
                'companies' => [
                    'description' => 'Submission is invalid.',
                    'details'     => $inputFilter->getMessages()
                ]
            ]);
        }
    }

    /**
     * @param int|string $id
     * @param mixed      $data
     *
     * @return JsonModel
     */
    public function update($id, $data)
    {
        $this->getLogger()->debug('PlayersController::update() start.');

        $data['id'] = (int) $id;

        $inputFilter = new PlayerInputFilter($this->getServiceLocator(), true);
        $inputFilter->setData($data);

        if ($inputFilter->isValid()) {
            $this->getLogger()->debug(self::LOGGER_INDENT . 'Input Filter is valid. Continue.');

            $player            = new Player($data);
            $player->updatedBy = $this->getCurrentPlayer()->id;
            $player            = $this->getPlayersTable()->setIndent(self::LOGGER_INDENT)->save($player);

            $this->getLogger()->debug('PlayersController::update() end.');

            return $this->statusOk([
                'entry'      => $player->toStdClass(),
                'pagination' => [
                    'pageNumber' => 1,
                    'pageSize'   => 1,
                    'totalItems' => 1,
                    'totalPages' => 1,
                ],
            ]);
        } else {
            $this->getLogger()->debug(self::LOGGER_INDENT . 'Input Filter is invalid. Will not update.');

            $this->getLogger()->debug('PlayersController::update() end.');

            return $this->statusBadRequest([
                'system'    => [
                    'id'          => 4001,
                    'description' => 'Invalid Request'
                ],
                'companies' => [
                    'description' => 'Submission is invalid.',
                    'details'     => $inputFilter->getMessages(),
                ]
            ]);
        }
    }

    /**
     * @param int|string $id
     *
     * @return JsonModel
     * @throws \Exception
     */
    public function delete($id)
    {
        $this->getLogger()->debug('PlayersController::delete() start.');

        $this->getLogger()->debug(self::LOGGER_INDENT . 'Getting info.');

        if ($id > 0) {
            $player = $this->getPlayersTable()->get($id);
            if ($player) {

                $this->getLogger()->debug(self::LOGGER_INDENT . 'Player ID       : ' . $id);
                $this->getLogger()->debug(self::LOGGER_INDENT . 'Player Username : ' . $player->username);
                $this->getLogger()->debug(self::LOGGER_INDENT . 'Player Full Name: ' . $player->fullName());
                $this->getLogger()->debug(self::LOGGER_INDENT . 'Player Email    : ' . $player->email);

                $player->deletedBy = $this->getCurrentPlayer()->id;
                $this->getPlayersTable()->setIndent(self::LOGGER_INDENT)->delete($player);

                $this->getLogger()->debug(self::LOGGER_INDENT . 'Player has been deleted.');
                $this->getLogger()->debug('PlayersController::delete() end.');

                return $this->statusOk([
                    'entry'      => null,
                    'pagination' => [
                        'pageNumber' => 1,
                        'pageSize'   => 1,
                        'totalItems' => 1,
                        'totalPages' => 1,
                    ],
                ]);
            } else {
                $this->getLogger()->debug(self::LOGGER_INDENT . 'Player ID ' . $id . ' does not exists.');
                $this->getLogger()->debug('PlayersController::delete() end.');

                return $this->statusNotFound();
            }
        } else {
            $this->getLogger()->debug(self::LOGGER_INDENT . 'Player ID is requred for deletion.');
            $this->getLogger()->debug('PlayersController::delete() end.');

            return $this->statusNotFound();
        }
    }

}
