<?php

namespace TdyCommons\Controller\Rest;

use TdyCommons\Controller\BaseRestController;
use TdyCommons\Model\DropdownList;
use TdyCommons\InputFilter\DropdownList as DropdownListInputFilter;
use TdyCommons\Table\DropdownLists;
use Zend\View\Model\JsonModel;

class DropdownListsController extends BaseRestController
{

    protected $identifierName = 'id';

    protected $dropdownListsTable;

    /**
     * @return DropdownLists
     */
    public function getDropdownListsTable()
    {
        if (!$this->gameAttributesTable) {
            $sm                        = $this->getServiceLocator();
            $this->gameAttributesTable = $sm->get('TdyCommons\Table\DropdownLists');
        }

        return $this->gameAttributesTable;
    }

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

        $dropdownLists = iterator_to_array($resultSet, false);

        /**
         * @var int          $k
         * @var DropdownList $dropdownList
         */
        foreach ($dropdownLists as $k => $dropdownList) {
            $dropdownLists[$k]->row = ++$i;
            $dropdownLists[$k]      = $dropdownList->toStdClass();
        }

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

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

        ]);
    }

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

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

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

        $data['id'] = 0;

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

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

            $data = $inputFilter->getValues();

            $dropdownList            = new DropdownList($data);
            $dropdownList->createdBy = $this->getCurrentPlayer()->id;

            $dropdownList = $this->getDropdownListsTable()->setIndent(self::LOGGER_INDENT)->save($dropdownList);

            $this->getLogger()->info(self::LOGGER_INDENT . 'DropdownList ' . $dropdownList->name . ' has been created.');
            $this->getLogger()->debug('DropdownListsController::create() end.');

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

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

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

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

            $dropdownList            = new DropdownList($data);
            $dropdownList->updatedBy = $this->getCurrentPlayer()->id;
            $dropdownList            = $this->getDropdownListsTable()->setIndent(self::LOGGER_INDENT)->save($dropdownList);

            $this->getLogger()->info(self::LOGGER_INDENT . 'DropdownList ' . $dropdownList->name . ' has been updated.');
            $this->getLogger()->debug('DropdownListsController::update() end.');

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

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

        if ($id > 0) {
            $dropdownList = $this->getDropdownListsTable()->get($id);
            if ($dropdownList) {

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

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

                $this->getLogger()->info(self::LOGGER_INDENT . 'DropdownList ' . $dropdownList->name . ' has been deleted.');
                $this->getLogger()->debug('DropdownListsController::delete() end.');

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

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

            return $this->statusNotFound();
        }
    }

}
