<?php

namespace TdySports\Controller\Rest;

use TdySports\Model\League;
use TdySports\InputFilter\League as LeagueInputFilter;
use TdyCommons\Controller\BaseRestController;
use Zend\View\Model\JsonModel;

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

    /**
     * @return JsonModel
     */
    public function getList()
    {
        $this->getLogger()->debug('LeaguesController::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->getLeaguesTable()->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;
        }

        $leagues = iterator_to_array($resultSet, false);

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

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

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

        ]);
    }

    /**
     * @param int|string $id
     *
     * @return JsonModel
     */
    public function get($id)
    {
        $league = $this->getLeaguesTable()->get($id);
        $league->setServiceLocator($this->getServiceLocator());

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

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

        $data['id'] = 0;

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

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

            $data = $inputFilter->getValues();

            $league            = new League($data);
            $league->createdBy = $this->getCurrentPlayer()->id;

            $league = $this->getLeaguesTable()->setIndent(self::LOGGER_INDENT)->save($league);

            $league->setServiceLocator($this->getServiceLocator());

            $this->getLogger()->info(self::LOGGER_INDENT . 'League ' . $league->name . ' has been created.');
            $this->getLogger()->debug('LeaguesController::create() end.');

            return $this->statusOk([
                'entry'      => $league->toStdClass(),
                'pagination' => [
                    'pageNumber' => 1,
                    'pageSize'   => 1,
                    'totalItems' => 1,
                    'totalPages' => 1,
                ],
            ]);
        } else {
            $this->getLogger()->debug(self::LOGGER_INDENT . 'Input Filter is invalid. Bugging out.');
            $this->getLogger()->debug('LeaguesController::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('LeaguesController::update() start.');

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

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

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

            $league            = new League($data);
            $league->updatedBy = $this->getCurrentPlayer()->id;
            $league            = $this->getLeaguesTable()->setIndent(self::LOGGER_INDENT)->save($league);

            $league->setServiceLocator($this->getServiceLocator());

            $this->getLogger()->info(self::LOGGER_INDENT . 'League ' . $league->name . ' has been updated.');
            $this->getLogger()->debug('LeaguesController::update() end.');

            return $this->statusOk([
                'entry'      => $league->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('LeaguesController::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('LeaguesController::delete() start.');

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

        if ($id > 0) {
            $league = $this->getLeaguesTable()->get($id);
            if ($league) {

                $this->getLogger()->debug(self::LOGGER_INDENT . 'League ID  : ' . $id);
                $this->getLogger()->debug(self::LOGGER_INDENT . 'League Name: ' . $league->name);

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

                $this->getLogger()->info(self::LOGGER_INDENT . 'League ' . $league->name . ' has been deleted.');
                $this->getLogger()->debug('LeaguesController::delete() end.');

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

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

            return $this->statusNotFound();
        }
    }

}
