<?php

namespace TdySports\Controller\Rest;

use TdySports\Model\Status;
use TdyCommons\Controller\BaseRestController;
use TdySports\Table\Statuses;
use Zend\View\Model\JsonModel;

class StatusesController extends BaseRestController
{

    /**
     * @var Statuses
     */
    protected $statusesTable;

    /**
     * @var string
     */
    protected $identifierName = 'id';

    /**
     * @return Statuses
     */
    public function getStatusesTable()
    {
        if (!$this->statusesTable) {
            $sm                  = $this->getServiceLocator();
            $this->statusesTable = $sm->get('TdySports\Table\Statuses');
        }

        return $this->statusesTable;
    }

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

        $statuses = iterator_to_array($resultSet, false);

        /**
         * @var int    $k
         * @var Status $status
         */
        foreach ($statuses as $k => $status) {
            $statuses[$k] = $status->toStdClass();
        }

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

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

        ]);
    }

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

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

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

        $data['id'] = 0;

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

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

            $data = $inputFilter->getValues();

            $status            = new Status($data);
            $status->createdBy = $this->getCurrentPlayer()->id;

            $status = $this->getStatusesTable()->setIndent(self::LOGGER_INDENT)->save($status);

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

            $this->getLogger()->info(self::LOGGER_INDENT . 'Status ' . $status->name . ' has been created.');
            $this->getLogger()->debug('StatusesController::create() end.');

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

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

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

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

            $status            = new Status($data);
            $status->updatedBy = $this->getCurrentPlayer()->id;
            $status            = $this->getStatusesTable()->setIndent(self::LOGGER_INDENT)->save($status);

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

            $this->getLogger()->info(self::LOGGER_INDENT . 'Status ' . $status->name . ' has been updated.');
            $this->getLogger()->debug('StatusesController::update() end.');

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

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

        if ($id > 0) {
            $status = $this->getStatusesTable()->get($id);
            if ($status) {

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

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

                $this->getLogger()->info(self::LOGGER_INDENT . 'Status ' . $status->name . ' has been deleted.');
                $this->getLogger()->debug('StatusesController::delete() end.');

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

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

            return $this->statusNotFound();
        }
    }

}
