<?php

namespace Diamond\Presentation\Modules\AdminStatRules;

use ActiveTable\ColumnTable;
use Core\Exceptions\ForbiddenAccessException;
use Core\Exceptions\TooManyRequestsException;
use Core\Form\ControlBuilder;
use Core\ModuleController;
use Diamond\Domain\StatRule\Contracts\StatRuleEntityInterface;
use Diamond\Domain\UserGroup\Contracts\UserGroupEntityInterface;
use Diamond\Repositories\StatRule\StatRuleCriteria;
use Diamond\Repositories\StatRule\StatRuleRepository;
use DiamondTable\TableFactory;

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

    private $statRuleRepository;
    private $tableFactory;
    private $controlBuilder;

    public function __construct(StatRuleRepository $statRuleRepository,
                                TableFactory       $tableFactory, ControlBuilder $builder)
    {
        $this->statRuleRepository = $statRuleRepository;
        $this->tableFactory = $tableFactory;
        $this->controlBuilder = $builder;
    }


    /**
     * @return string
     */
    public function process(): string
    {
        $table = $this->tableFactory->buildAdminTable($this->statRuleRepository, StatRuleCriteria::create());

        $table
            ->setDefaultSortColumn('id','DESC')
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
                    ->setSorted(true)
            )
            ->addColumn(
                (new ColumnTable('name', 'Правило'))
                    ->setSorted(true)
            )
            ->addColumn(
                (new ColumnTable('clientType', 'Тип клиента'))->setFormat($this, 'formatType')
            )
            ->addColumn(
                (new ColumnTable('uriMask', 'Маска url страницы'))

            )
            ->addColumn(
                (new ColumnTable('ipMask', 'Маска ip адреса'))

            )
            ->addColumn(
                (new ColumnTable('hostMask', 'Маска хоста'))

            )
            ->addColumn(
                (new ColumnTable('agentMask', 'Браузер/агент'))

            )
            ->addColumn(
                (new ColumnTable('rule', 'Правило'))->setFormat($this, 'formatRule')

            )
            ->addColumn(
                (new ColumnTable('period', 'Период проверки, сек'))

            )
            ->addColumn(
                (new ColumnTable('banRate', 'Кол-во посещений за период, сек'))

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

        $table
            ->addField(
                $this->controlBuilder->buildInput('name'), true
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('clientType', self::types()), true
            )
            ->addField(
                $this->controlBuilder->buildInput('uriMask')->setValue('%'), true, null, '% для любого'
            )
            ->addField(
                $this->controlBuilder->buildInput('ipMask')->setValue('%'), true, null, '% для любого'
            )
            ->addField(
                $this->controlBuilder->buildInput('hostMask')->setValue('%'), true, null, '% для любого'
            )
            ->addField(
                $this->controlBuilder->buildInput('agentMask')->setValue('%'), true, null, '% для любого'
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('rule', self::rules()), true
            )
            ->addField(
                $this->controlBuilder->buildInput('period')->setValue('60'), false, null
            )
            ->addField(
                $this->controlBuilder->buildInput('banRate')->setValue('5'), false, null
            );

        return $table->render();
    }

    protected static function rules(): array
    {
        return [
            'DENY' => 'Запретить',
            'NO_STAT' => 'Не собирать статистику',
            'NOTIFY' => 'Вывести уведомление с проверочным кодом',
            'ACCESS' => 'Разрешить',
        ];
    }

    protected static function types(): array
    {
        return [
            '%' => 'Любой',
            'mobile' => 'Мобильный',
            'browser' => 'Браузер',
            'robot' => 'Бот'
        ];
    }

    public function formatType(StatRuleEntityInterface $userEntity): string
    {
        $rules = self::types();
        return $rules[$userEntity->getClientType()] ?? '-';
    }

    public function formatRule(StatRuleEntityInterface $userEntity): string
    {
        $rules = self::rules();
        return $rules[$userEntity->getRule()] ?? '-';
    }

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