<?php

namespace Shop\Modules\AdminCategories;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\Form\ControlBuilder;
use Core\Helpers\Text;
use Core\ModuleController;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;
use Shop\Domain\Catalog\Contracts\CatalogEntityInterface;
use Shop\Domain\ProductCategory\Contracts\ProductCategoryEntityInterface;
use Shop\Repositories\Catalog\CatalogCriteria;
use Shop\Repositories\Catalog\CatalogRepository;
use Shop\Repositories\ProductCategory\ProductCategoryCriteria;
use Shop\Repositories\ProductCategory\ProductCategoryRepository;

/**
 * Description of AdminCategories
 *
 * @author Dmitriy
 */
class AdminCategories extends ModuleController implements RequestAwareInterface
{

    use RequestAwareTrait;
    protected $productCategoryRepository;
    protected $tableFactory;
    protected $controlBuilder;
    protected $catalogRepository;

    public function __construct(ProductCategoryRepository $productCategoryRepository, CatalogRepository $catalogRepository,TableFactory $tableFactory,
                                ControlBuilder $controlBuilder)
    {
        $this->productCategoryRepository = $productCategoryRepository;
        $this->catalogRepository = $catalogRepository;
        $this->controlBuilder = $controlBuilder;
        $this->tableFactory = $tableFactory;
    }


    /**
     * @param ProductCategoryEntityInterface $categoryEntity
     * @return string
     */
    public function formatParent(ProductCategoryEntityInterface $categoryEntity): string
    {
        if (!$categoryEntity->getParentCategory()) {
            return '';
        }
        return $categoryEntity->getParentCategory()->getTitle();
    }

    /**
     * @param ProductCategoryEntityInterface $categoryEntity
     * @return string
     */
    public function formatDesc(ProductCategoryEntityInterface $categoryEntity): string
    {
        if (!$text = $categoryEntity->getDesc()) {
            return '';
        }
        return Text::clearText($text);
    }

    public function process(): string
    {

        $list = $this->productCategoryRepository->findByCriteria(
            ProductCategoryCriteria::create()
        );
        $listCatalog = $this->catalogRepository->findByCriteria(
            CatalogCriteria::create()
        );

        $catalogAr = Form::prepareDropdown($listCatalog);
        $listAr = Form::prepareDropdownWithDef($list,'NULL', 'без родительского', 'getDropdownListWithParent');

        if (input_get('id') > 0) {
            unset($listAr[input_get('id')]);
        }


        $table = $this->tableFactory->buildAdminTable($this->productCategoryRepository,
            ProductCategoryCriteria::create()->setAsTreeView(true)->setLimit(1000));

        $table
            ->removeControlAccess(DataTableEngine::CONTROL_ROWS_SELECT)
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
//            ->addColumn(
//                (new ColumnTable('parent', 'Родитель'))
//                    ->setFormat($this, 'formatParent')
//                    ->setWidth(10, true)
//            )
            ->addColumn(
                (new ColumnTable('title', 'Наименование'))
                    ->setFormat($this, 'formatTitle')
            )
            ->addColumn(
                (new ColumnTable('alias', 'Псевдоним'))
            )
            ->addColumn(
                (new ColumnTable('image', 'Изображение'))
            )
            ->addColumn(
                (new ColumnTable('desc', 'Описание'))
                    ->setFormat($this, 'formatDesc')
            )
            ->addColumn(
                (new ColumnTable('catalog', 'Каталог'))
                    ->setFormat($this, 'formatCatalog')
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setFormat($this, 'formatActions')
                    ->setWidth(140)
            );

//            ->addRowActionCommand(
//                'change-catalog',
//                new ChangeCatalogCommand($table, $this->buildMoveBrandForm($catalogAr)),
//                'Сменить каталог'
//            );

        $table
            ->addField(
                $this->controlBuilder
                    ->buildInput('title'), true
            )
            ->addField(
                $this->controlBuilder
                    ->buildInput('alias'), true, 'Псевдоним на латинице','для использования в ЧПУ'
            )
            ->addField(
                $this->controlBuilder
                    ->buildDropdownUniform('parentId', $listAr)
                    ->setValue($this->request->query->get('parent_id')??'NULL')
                , false, 'Родительский раздел'
            )
            ->addField(
                $this->controlBuilder
                    ->buildDropdownUniform('catalogId', $catalogAr)
                    ->setValue($this->request->query->get('catalog_id')??'NULL')
                , true, 'Каталог'
            )
            ->addField(
                $this->controlBuilder
                    ->buildTextEditor('desc')
                    ->setHeight(200)
                    ->setCompact(true)
            );


//        $this->buildForm($table, $catalogAr);

        return $table->render();
    }

    /**
     * @param ProductCategoryEntityInterface $categoryEntity
     * @return string
     */
    public function formatActions(ProductCategoryEntityInterface $categoryEntity): string
    {
        $id = $categoryEntity->getId();

        return $this->controlBuilder->buildActionMenuAdmin([
            anchor(
                adaptive_url([
                    'fn' => 'add',
                    'parent_id' => $id
                ]),
                'Добавить подраздел'),

        ], $id)->render();
    }

    /**
     * @param ProductCategoryEntityInterface $categoryEntity
     * @return string
     */
    public function formatTitle(ProductCategoryEntityInterface $categoryEntity): string
    {

        $title = $categoryEntity->getTitle();

        return $categoryEntity->getCountChildrens() > 0 ?
            '<i class="sprite folder interval10right"></i>' .
            $title : ($categoryEntity->getParentId() > 0 ? nbs(7) : '') .
            $title;
    }

    /**
     * @param ProductCategoryEntityInterface $product
     * @return string
     */
    public function formatCatalog(ProductCategoryEntityInterface $category): string
    {
        return is_object($category->getCatalog()) ? $category->getCatalog()->getName() : '';
    }

}