<?php

namespace TdySports\Controller\Rest;

use TdySports\Model\Group;
use TdySports\InputFilter\Group as GroupInputFilter;
use TdyCommons\Controller\BaseRestController;
use Zend\View\Model\JsonModel;

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

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

        $groups = iterator_to_array($resultSet, false);

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

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

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

        ]);
    }

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

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

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

        $data['id'] = 0;

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

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

            $data = $inputFilter->getValues();

            $group            = new Group($data);
            $group->createdBy = $this->getCurrentPlayer()->id;

            $group = $this->getGroupsTable()->setIndent(self::LOGGER_INDENT)->save($group);

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

            $this->getLogger()->info(self::LOGGER_INDENT . 'Group ' . $group->name . ' has been created.');
            $this->getLogger()->debug('GroupsController::create() end.');

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

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

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

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

            $group            = new Group($data);
            $group->updatedBy = $this->getCurrentPlayer()->id;
            $group            = $this->getGroupsTable()->setIndent(self::LOGGER_INDENT)->save($group);

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

            $this->getLogger()->info(self::LOGGER_INDENT . 'Group ' . $group->name . ' has been updated.');
            $this->getLogger()->debug('GroupsController::update() end.');

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

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

        if ($id > 0) {
            $group = $this->getGroupsTable()->get($id);
            if ($group) {

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

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

                $this->getLogger()->info(self::LOGGER_INDENT . 'Group ' . $group->name . ' has been deleted.');
                $this->getLogger()->debug('GroupsController::delete() end.');

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

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

            return $this->statusNotFound();
        }
    }

}
