<?php

namespace Diamond\Modules\AdminTemplates;

use ActiveTable\ColumnTable;
use Core\ModuleController;
use Core\Form\ControlBuilder;
use Diamond\Domain\Template\Contracts\TemplateEntityInterface;
use Diamond\Repositories\Template\TemplateCriteria;
use Diamond\Repositories\Template\TemplateRepository;
use DiamondTable\TableFactory;

/**
 * Description of AdminTemplates
 *
 * @author Diamond Code Generator
 */
class AdminTemplates extends ModuleController
{

    public function __construct(private TemplateRepository $repo,
                                private ControlBuilder $controlBuilder,
                                private TableFactory $tableFactory)
    {}


    public function process(): string
    {
        $table = $this->tableFactory->buildAdminTable($this->repo, TemplateCriteria::create(), 'Создать шаблон');
        
        $table
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('name', 'Идентификатор'))
            )
            ->addColumn(
                (new ColumnTable('code', 'Расположение'))
            )
            ->addColumn(
                (new ColumnTable('description', 'Описание'))
                    ->setFormat($this, 'formatDesc')

            )
            ->addField(
                $this->controlBuilder->buildInput('name'), true, null, 'Уникальный для каждого сайта'
            )
            ->addField(
                $this->controlBuilder->buildInput('code'), true, null, 'Уникальный для каждого сайта'
            )
            ->addField(
                $this->controlBuilder->buildTextArea('description')
            );

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

        $table
            ->addColumn(
                (new ColumnTable('action', ''))
                    ->setWidth(120)
                    ->setFormat($this, 'formatActions')
            );

        return $table->render();
    }

    public function formatActions(TemplateEntityInterface $entity): string
    {
        return $this->controlBuilder->buildActionMenuAdmin([], $entity->getId())->render();
    }

    public function formatDesc(\Diamond\Infrastructure\Models\Template\Template $template): string
    {
        return trim(str_replace(array('\r\n', '\n'), '',
            \Diamond\Helpers\Text::characterlimiter(strip_tags($template->getDescription()), 80)));
    }

}               