<?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\Product\ProductCriteria;
use Shop\Repositories\Product\ProductRepository;
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;
    protected $productRepository;

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


    /**
     * @param ProductCategoryEntityInterface $categoryEntity
     * @return string
     * @throws \Propel\Runtime\Exception\PropelException
     */
    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);

        $this->prepareColumns($table);
//            ->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)
            );

        $table
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_title')
            );


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

        return $table->render();
    }

    protected function prepareColumns(DataTableEngine $table): void
    {
        $table
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('title', 'Наименование'))
                    ->setFormat($this, 'formatTitle')
            )
            ->addColumn(
                (new ColumnTable('parent', 'Родитель'))
                    ->setFormat($this, 'formatParent')
            )
            ->addColumn(
                (new ColumnTable('alias', 'Псевдоним'))
            )
            ->addColumn(
                (new ColumnTable('products', 'Товаров'))
                    ->setFormat($this, 'formatProducts')
                    ->setWidth(10, true)
            )
            ->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)
            );
    }

    /**
     * @param ProductCategoryEntityInterface $categoryEntity
     * @return string
     */
    public function formatProducts(ProductCategoryEntityInterface $categoryEntity): string
    {
        $count = $this->productRepository->count(
            ProductCriteria::create()->setFilterByCategoryId($categoryEntity->getId())
        );

        return (string)$count;
    }

    /**
     * @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
                ]),
                Form::buildIconText('pencil_white', 'Добавить подраздел')),

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

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

        $title = $categoryEntity->getTitle();

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

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

}