<?php

namespace Diamond\Modules\AdminStat;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\ModuleController;
use Diamond\Domain\Stat\Contracts\StatEntityInterface;
use DiamondTable\TableFactory;
use Core\Form\ControlBuilder;
use Diamond\Repositories\Stat;
use Diamond\Helpers\Date;

/**
 * Description of AdminUsers
 *
 * @author Dmitriy
 */
class AdminStat extends ModuleController
{

    public function __construct(private Stat\StatRepository $repo, private TableFactory $tableFactory, private ControlBuilder $controlBuilder)
    {
    }


    public function process(): string
    {

        $table = $this->tableFactory->buildAdminTable($this->repo, Stat\StatCriteria::create());

        $table
            ->removeControlAccess(DataTableEngine::CONTROL_ACCESS_ADD)
            ->removeControlAccess(DataTableEngine::CONTROL_ROWS_ACTION)
            ->removeControlAccess(DataTableEngine::CONTROL_FORM_SAVE_BUTTON)
            ->removeControlAccess(DataTableEngine::CONTROL_ACCESS_DELETE)
            ->setDefaultSortColumn('id', 'DESC')
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
                    ->setSorted(true)
            )
            ->addColumn(
                (new ColumnTable('datetime', 'Дата'))
                    ->setFormat($this, 'formatDate')
                    ->setSorted(true)
            )
            ->addColumn(
                (new ColumnTable('remoteaddr', 'IP адрес'))
            )
            ->addColumn(
                (new ColumnTable('requesturi', 'Страница  и параметры запроса'))

            )
            ->addColumn(
                (new ColumnTable('requestmethod', 'Метод запроса'))

            )
            ->addColumn(
                (new ColumnTable('useragent', 'Клиент'))

            )
            ->addColumn(
                (new ColumnTable('elapsedtime', 'Время, сек'))

            )
            ->addColumn(
                (new ColumnTable('memory', 'Память, Мб'))

                    ->setFormat($this, 'formatMemory')
            )
            ->addColumn(
                (new ColumnTable('clientuser', 'Публич. польз.'))

            )
            ->addColumn(
                (new ColumnTable('adminuser', 'Админ. польз.'))

            )
            ->addColumn(
                (new ColumnTable('host', 'Хост'))
            )
            ->addColumn(
                (new ColumnTable('referer', 'Откуда'))
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setWidth(120)
                    ->setFormat($this, 'formatActions')
            )

            ->addFilter(
                $this->controlBuilder->buildDropdownUniform('filter_by_requestmethod',[
                    null => 'все',
                    'GET'   =>  'GET',
                    'POST'   =>  'POST'
                ])
            )
            ->addFilter(
                $this->controlBuilder->buildInput('filter_by_remoteaddr')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_requesturi')
            )

            ->addField($this->controlBuilder->buildTextLabel("datetime")->setFn($this,'formatDate'))
            ->addField($this->controlBuilder->buildTextLabel("remoteaddr"))
            ->addField($this->controlBuilder->buildTextLabel("requestedpage"),false,'Страница')
            ->addField($this->controlBuilder->buildTextLabel("requesturi"))
            ->addField($this->controlBuilder->buildTextLabel("useragent"))
            ->addField($this->controlBuilder->buildTextLabel("requestmethod"))
            ->addField($this->controlBuilder->buildTextLabel("referer"),false,'Переход с')
            ->addField($this->controlBuilder->buildTextLabel("elapsedtime"))
            ->addField($this->controlBuilder->buildTextLabel("memory")->setFn($this,'formatMemory'))
            ->addField($this->controlBuilder->buildTextLabel("requestmethod"))
            ->addField($this->controlBuilder->buildTextLabel("clienttype"),false,'Тип клиента')
            ->addField($this->controlBuilder->buildTextLabel("client"),false,'Клиент')
            ->addField($this->controlBuilder->buildTextLabel("platform"),false,'Платформа')
            ->addField($this->controlBuilder->buildTextLabel("clientuser"),false,null,'Пользователь публичной части')
            ->addField($this->controlBuilder->buildTextLabel("adminuser"),false,null,'Пользователь административной части')
            ->addField($this->controlBuilder->buildTextLabel("postdata")->setFn($this,'formatPostData'))
        ;

        return $table->render();
    }


    public function formatActions(StatEntityInterface $statEntity): string
    {
        return $this->controlBuilder->buildActionMenu([anchor(
            adaptive_url([
                'fn' => 'edit',
                'id' => $statEntity->getId()
            ]),
            'Просмотр')])->render();
    }


    public function getRepo()
    {
        return $this->statRepo->setSelectFilter(function (\Diamond\Infrastructure\Models\Stat\StatQuery $query) {
            return $query->orderById(\Propel\Runtime\ActiveQuery\Criteria::DESC);
        });
    }


    public function formatMemory(\Diamond\Infrastructure\Models\Stat\Stat $stat): string
    {
        return round($stat->getMemory() / 1024 / 1024, 2);
    }


    public function formatDate(StatEntityInterface $stat): string
    {
        return $stat->getDatetime(Date::formatDisplay());
    }

    public function formatPostData(\Diamond\Infrastructure\Models\Stat\Stat $stat): string
    {
        ob_start();
        dump(json_decode($stat->getPostData()));
        $buffer = ob_get_clean();
        return $buffer;
    }
}
