<?php

namespace TdySports\Controller\Rest;

use TdySports\Model\Team;
use TdySports\InputFilter\Team as TeamInputFilter;
use TdyCommons\Controller\BaseRestController;
use Zend\View\Model\JsonModel;

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

    /**
     * @return JsonModel
     */
    public function getList()
    {
        $this->getLogger()->debug('TeamsController::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->getTeamsTable()->setIndent(self::LOGGER_INDENT)->fetch($q, $x, $f, $s, $l > 0);

        if ($l > 0) {
            $resultSet->setCurrentPageNumber((int) $p);
            $resultSet->setItemCountPerPage($l);
        }

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

        $teams = iterator_to_array($resultSet, false);

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

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

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

        ]);
    }

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

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

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

        $data['id'] = 0;

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

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

            $data = $inputFilter->getValues();

            $team            = new Team($data);
            $team->createdBy = $this->getCurrentAdmin()->id;

            $team = $this->getTeamsTable()->setIndent(self::LOGGER_INDENT)->save($team);

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

            $this->getLogger()->info(self::LOGGER_INDENT . 'Team ' . $team->name . ' has been created.');
            $this->getLogger()->debug('TeamsController::create() end.');

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

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

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

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

            $team            = new Team($data);
            $team->updatedBy = $this->getCurrentAdmin()->id;
            $team            = $this->getTeamsTable()->setIndent(self::LOGGER_INDENT)->save($team);

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

            $this->getLogger()->info(self::LOGGER_INDENT . 'Team ' . $team->name . ' has been updated.');
            $this->getLogger()->debug('TeamsController::update() end.');

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

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

        if ($id > 0) {
            $team = $this->getTeamsTable()->get($id);
            if ($team) {

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

                $team->deletedBy = $this->getCurrentAdmin()->id;
                $this->getTeamsTable()->setIndent(self::LOGGER_INDENT)->delete($team);

                $this->getLogger()->info(self::LOGGER_INDENT . 'Team ' . $team->name . ' has been deleted.');
                $this->getLogger()->debug('TeamsController::delete() end.');

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

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

            return $this->statusNotFound();
        }
    }

}
