<?php

declare(strict_types=1);

namespace portalpeople\consoletools;

use portalpeople\consoletools\services\ConsoleService;
use Yii;
use yii\base\BootstrapInterface;
use yii\base\Module as BaseModule;
use yii\web\Application as WebApplication;

class Module extends BaseModule implements BootstrapInterface
{
    public string $moduleId = 'ngauge-console-tools';
    public bool $enabled = true;
    public $controllerNamespace = 'portalpeople\\consoletools\\controllers';

    private ?ConsoleService $consoleService = null;

    public function init(): void
    {
        parent::init();

        /** @var array<string, mixed> $config */
        $config = Yii::$app->params['plugins']['ngauge-console-tools'] ?? [];

        if (isset($config['enabled'])) {
            $this->enabled = (bool) $config['enabled'];
        }
    }

    public function bootstrap($app): void
    {
        if (!isset($app->getModules()['ngauge-console-tools'])) {
            $app->setModule('ngauge-console-tools', [
                'class' => self::class,
            ]);
        }

        if ($app instanceof WebApplication && $app->has('urlManager')) {
            $app->getUrlManager()->addRules([
                'GET v1/console/giimodel' => 'ngauge-console-tools/api/console/giimodel',
            ], false);
        }
    }

    public function getConsoleService(): ConsoleService
    {
        if ($this->consoleService === null) {
            $this->consoleService = new ConsoleService();
        }

        return $this->consoleService;
    }
}
