<?php

namespace Diamond\Modules\StatChart;

use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\Form\Control\Dropdown;
use Core\Template\Template;

/**
 * Description of AdminAuth
 *
 * @author Dmitriy
 */
class StatChart extends \Core\ModuleController implements RequestAwareInterface
{

    use RequestAwareTrait;

    public int $height = 300;
    public string $id = 'chartplace';
    public int $interval = 60;
    public string $url = '/_service/diamond/stat/requests';
    public bool $control = false;
    public bool $hideTime = false;
    public int|null $maxTime = null;
    public string|null $title = null;
    public string|null $pageUrl = null;

    /**
     * StatChart constructor.
     * @param Template $template
     */
    public function __construct(protected Template $template)
    {

    }

    public function process(): string
    {
        $post = $this->request->request->all();
        $interval = $post['interval'] ?? $this->interval;
        $maxTime = $post['max-time'] ?? $this->maxTime;

        $this->template->addScriptLink('/_diamond/widgets/assets/jquery/flot/flot.min.js');
        $this->template->addScriptLink('/_diamond/widgets/assets/jquery/flot/flot.resize.min.js');

        $this->template->addScript($this->render('javascript',
            [
                'interval' => $interval,
                'maxTime' => $this->hideTime === true || !$maxTime ? '' : $maxTime,
                'url' => $this->url,
                'id' => $this->id,
                'minTickSize' => $interval <= 7 ? 'hour' : 'day'
            ]));

        $name = $interval === $this->interval ? 'sel' : 'sel' . $interval;

        $dropdownPeriod
            = (new Dropdown('interval', [
                '120' => '3 месяца',
                '30' => '1 месяц',
                '7' => '1 наделя',
                '1' => '1 день'
            ]))
            ->setClass('form-control')
            ->onChange("jQuery('#interval').submit();");

        $timeDropdown
            = (new Dropdown('max-time', [
                '60' => '60 сек',
                '120' => '120 сек',
                '240' => '4 мин',
                '480' => '8 мин',
                '960' => '16 мин',
                '3600' => '1 час'
            ]))
            ->setClass('form-control')
            ->onChange("jQuery('#interval').submit();");;

        return $this->render([
            'title' => $this->title,
            'intervalDropdown' => $dropdownPeriod->render(),
            'timeDropdown' => $this->hideTime === true ? "" : $timeDropdown->render(),
            'height' => $this->height,
            'id' => $this->id,
            'control' => $this->control,
            'interval' => $this->interval,
            $name => 'selected',
            'page_url' =>  $this->pageUrl
        ]);
    }

}