<?php

namespace PortalPeople\queues\controllers;

use PortalPeople\queues\services\QueueMonitorService;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Response;

class MonitorController extends Controller
{
    public function behaviors()
    {
        $rules = [
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ];

        if (class_exists('\\common\\models\\Permissions') && method_exists('\\common\\models\\Permissions', 'getPermissions')) {
            $rules = \common\models\Permissions::getPermissions(self::class);
        }

        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => $rules,
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'index' => ['GET'],
                    'status' => ['GET'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index', [
            'dashboard' => $this->monitorService()->getDashboardData(),
        ]);
    }

    public function actionStatus()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        return $this->monitorService()->getDashboardData();
    }

    protected function monitorService(): QueueMonitorService
    {
        $componentId = 'ngaugeQueueMonitor';

        if ($this->module !== null && property_exists($this->module, 'monitorComponentId')) {
            $componentId = $this->module->monitorComponentId;
        }

        return Yii::$app->get($componentId);
    }
}
