<?php declare(strict_types=1);

namespace Diamond\Modules\AdminMenu;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\Form\Control\MenuItem;
use Core\Form\Control\Switchery;
use Core\Form\NiftyControlBuilder;
use Core\Helpers\Text;
use Core\ModuleController;
use Diamond\Domain\Menu\Contracts\MenuEntityInterface;
use Diamond\Helpers\Form;
use Diamond\Repositories\Menu\MenuCriteria;
use Diamond\Repositories\Menu\MenuRepository;
use DiamondTable\TableFactory;

/**
 * Description of AdminMenu
 *
 * @author Diamond Code Generator
 */
class AdminMenu extends ModuleController implements RequestAwareInterface
{
    use RequestAwareTrait;

    public function __construct(private MenuRepository $menuRepository,
                                private  TableFactory $tableFactory,
                                private NiftyControlBuilder $controlBuilder)
    {}


    public function process(): string
    {

        $criteria = MenuCriteria::create()->setTreeView(true)->setLimit(1000);


        $table = $this->tableFactory->buildAdminTable($this->menuRepository, $criteria);
        $table->removeControlAccess(DataTableEngine::CONTROL_ROWS_SELECT);

        $table
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('title', 'Наименование'))
                    ->setFormat($this, 'formatName')
                    //->setWidth(40,true)
            )
            ->addColumn(
                (new ColumnTable('url', 'Адрес'))
            )
            ->addColumn(
                (new ColumnTable('name', 'Наименование'))
            )
            ->addColumn(
                (new ColumnTable('desc', 'Описание'))->setFormat($this, 'formatDesc')
            )
            ->addColumn(
                (new ColumnTable('position', 'Порядок'))
            )
            ->addColumn(
                (new ColumnTable('active', 'Включено'))
                    ->setFormat($this, 'formatActive')
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setFormat($this, 'formatActions')
                    ->setWidth(120)
            );

        $table
            ->addField(
                $this->controlBuilder->buildInput('title'), true
            )
            ->addField(
                $this->controlBuilder->buildInput('url')
            )
            ->addField(
                $this->controlBuilder->buildInput('name'), false, null, 'техническое имя'
            )
            ->addField(
                $this->controlBuilder->buildInput('code'), false, 'Идентификатор', 'указывать необязательно'
            )
            ->addField(
                $this->controlBuilder->buildInput('desc'), false, 'Описание'
            )
            ->addField(
                $this->controlBuilder->buildNiftySimpleSwitchery('active','Y','N'), true, 'Опубликованно'
            )
            ->addField(
                $this->controlBuilder->buildInput('position')//buildSpinner
            )
        ;


        $menu = $this->menuRepository->findByCriteria(MenuCriteria::create()->setTreeView(true)->setLimit(1000));

        $menuCollection = clone $menu;

        foreach ($menu as $item) {
            //$item->setTitle($item->getTitle().sprintf(' [%s]',$item->getName()));
            //$menuCOllection->offsetSet($item);
            if ($item->getId() === (int)$this->request->get('id')) {
                $menuCollection->offsetUnset($item);
            }
        }


        $table->addField(
            $this->controlBuilder
                ->buildDropdownUniform('parentId', Form::prepareDropdown($menuCollection))
                ->setValue($this->request->query->get('parent_id'))
            ,
            false,
            'Родительский элемент'
        );

        $table
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_name')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_url')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_title')
            )
            ->addFilter(
                $this->controlBuilder->buildDropdownYNUniform('filter_by_active',[null=>'все'])
            )
        ;

        $this->tableFactory->prepareAdminTableForDomain($table);

        return $table->render();
    }
    public function formatDesc(MenuEntityInterface $menuEntity): string
    {
        if(!$menuEntity->getDesc()){
            return '';
        }
        return Text::clearText($menuEntity->getDesc()??'',30).'...';
    }
    public function formatName(MenuEntityInterface $menuEntity): string
    {
        return $menuEntity->getCountChildrens() > 0 ?
            '<i class="sprite folder interval10right"></i>' .
            $menuEntity->getTitle() : ($menuEntity->getParentId() > 0 ? nbs(7): '')  . '<i class="sprite pointer"></i>' . $menuEntity->getTitle();
    }

    public function formatActive(MenuEntityInterface $item): string
    {
        $data = [
            'class' => self::class,
            'id' => $item->getId(),
            'fn' => 'changeActive'
        ];
        return (new Switchery($data, $item->getActive() === 'Y'))->render();
    }

    public function changeActive(int $id, bool $checked): void
    {
        $item = $this->menuRepository ->findById($id);
        $item->setActive($checked === true ? 'Y' : 'N');
        $this->menuRepository->save($item);
    }

    public function formatActions(MenuEntityInterface $menuEntity): string
    {
        $id = $menuEntity->getId();

        return $this->controlBuilder->buildActionMenuAdmin([
            new MenuItem(adaptive_url([
                'fn' => 'add',
                'parent_id' => $id
            ]),'Добавить дочерний','fa fa-clone'),
            new MenuItem(adaptive_url([
                'fn' => 'add',
                'id' => $menuEntity->getId()
            ]), 'Скопировать','fa fa-copy')
        ], $id)->render();
    }

}               