<?php


namespace App\Components\DataGrids;


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

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

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

    protected function setupColumns(DataGrid $grid)
    {
        $this->columnIdPreset($grid);
        $this->columnNamePreset($grid, true);
        $grid->addColumnText('identifier', 'API identifier', 'apiIdentifier');
        $this->columnStatusPreset($grid);
    }

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

    public function setupAdder(Container $container)
    {
        $container->addText('name', '');
        $container->addText('identifier', '');
    }

    protected function processAdder($values)
    {
        $this->gameFacade->getRegionWriter()->createRegion($this->game, $values->name, $values->identifier);
    }

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

    /**
     * @param $id
     * @param $value
     */
    public function editIdentifier($id, $value)
    {
        try {
            $this->gameFacade->getRegionWriter()->editApiIdentifier($id, $value);
        } catch (Throwable $e) {
            Debugger::log($e);
            $this->getPresenter()->flashMessage('Identifier editing has failed.', FlashMessage::ERROR);
        } finally {
            $this->redrawFlashMessages();
            $this->redrawRow($id);
        }
    }
}