<?php

namespace TdySports\Controller\Rest;

use TdySports\Model\Sport;
use TdySports\InputFilter\Sport as SportInputFilter;
use TdyCommons\Controller\BaseRestController;
use Zend\View\Model\JsonModel;

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

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

        $sports = iterator_to_array($resultSet, false);

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

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

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

        ]);
    }

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

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

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

        $data['id'] = 0;

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

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

            $data = $inputFilter->getValues();

            $sport            = new Sport($data);
            $sport->createdBy = $this->getCurrentPlayer()->id;

            $sport = $this->getSportsTable()->setIndent(self::LOGGER_INDENT)->save($sport);

            $this->getLogger()->info(self::LOGGER_INDENT . 'Sport ' . $sport->name . ' has been created.');
            $this->getLogger()->debug('SportsController::create() end.');

            return $this->statusOk([
                'entry'      => $sport->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('SportsController::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('SportsController::update() start.');

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

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

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

            $sport            = new Sport($data);
            $sport->updatedBy = $this->getCurrentPlayer()->id;
            $sport            = $this->getSportsTable()->setIndent(self::LOGGER_INDENT)->save($sport);

            $this->getLogger()->info(self::LOGGER_INDENT . 'Sport ' . $sport->name . ' has been updated.');
            $this->getLogger()->debug('SportsController::update() end.');

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

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

        if ($id > 0) {
            $sport = $this->getSportsTable()->get($id);
            if ($sport) {

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

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

                $this->getLogger()->info(self::LOGGER_INDENT . 'Sport ' . $sport->name . ' has been deleted.');
                $this->getLogger()->debug('SportsController::delete() end.');

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

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

            return $this->statusNotFound();
        }
    }

}
