<?php


namespace App\Components\DataGrids;


use App\Model\Enums\FlashMessage;
use App\Model\Facades\GameFacade;
use App\Model\Translator;
use DateTime;
use Kdyby\Doctrine\QueryBuilder;
use Nette\Forms\Container;
use RadekDostal\NetteComponents\DateTimePicker\TbDatePicker;
use Throwable;
use Tracy\Debugger;
use Ublaboo\DataGrid\DataGrid;

class PlatformsDataGrid extends BaseDataGrid
{
    /** @var GameFacade */
    protected $gameFacade;

    public function __construct(Translator $translator, GameFacade $gameFacade)
    {
        parent::__construct($translator);
        $this->gameFacade = $gameFacade;
        $this->enableAdder();
    }

    protected function setupDataSource() : QueryBuilder
    {
        return $this->gameFacade->getPlatformReader()->getGridDataSource();
    }

    protected function setupColumns(DataGrid $grid)
    {
        $this->columnIdPreset($grid);
        $this->columnNamePreset($grid, true);
        $grid->addColumnDateTime('releasedOn', 'Released on', 'releasedOn')->setFormat('j. n. Y');
        $this->columnStatusPreset($grid);

        $grid->getColumn('name')->getElementPrototype('th')->class('col-xs-6');
        $grid->getColumn('releasedOn')->getElementPrototype('th')->class('col-xs-6');
    }

    protected function setupInlineEdit(DataGrid $grid)
    {
        $grid->getColumn('releasedOn')
            ->setEditableCallback([$this, 'editReleasedOn'])
            ->setEditableInputType('text', ['class' => 'form-control input-sm datepicker']);
    }

    public function setupAdder(Container $container)
    {
        TbDatePicker::register();

        $container->addText('name', '');
        $container->addTbDatePicker('releasedOn', '')
            ->setAttribute('class', 'form-control datepicker');
    }

    protected function processAdder($values)
    {
        $this->gameFacade->getPlatformWriter()->createPlatform($values->name, $values->releasedOn);
    }

    protected function editName(int $id, string $name)
    {
        $this->gameFacade->getPlatformWriter()->editName($id, $name);
    }

    public function editReleasedOn(int $id, $date)
    {
        try {
            $this->gameFacade->getPlatformWriter()->editReleasedOn($id, DateTime::createFromFormat('j. n. Y', $date));
        } catch (Throwable $e) {
            Debugger::log($e);
            $this->getPresenter()->flashMessage('Date editing has failed.', FlashMessage::ERROR);
        } finally {
            $this->redrawFlashMessages();
            $this->redrawRow($id);
        }
    }

    protected function statusChange(int $id, string $status)
    {
        $this->gameFacade->getPlatformWriter()->editState($id, $status);
    }
}