<?php

namespace Plugin\LyMaster\plugin;

use APP\program\admin\Plugin;
use APP\program\admin\Setting;
use Exception;
use LyApi\core\design\Register;
use LyApi\logger\Logger;

/**
 * Name: LyMaster.plugin.Processor
 * Author: LyAPI
 * ModifyTime: 2020/05/03
 * Purpose: 插件功能管理器
 */

class Manager
{

    private $listens = [];
    private $errors = [];

    // 用于注册所有数据
    public function registerAll()
    {
        $db_connect = Setting::dbConnect();
        $plugins = $db_connect->select('plugin', ['id', 'path']);

        if ($plugins == null) {
            return;
        }

        foreach ($plugins as $key => $value) {
            $mnsp = "Admin\\plugin\\" . $value['path'];
            if (class_exists($mnsp . '\\' . 'options')) {
                if (Plugin::isOpen($value['id'], 'id')) {
                    $class = $mnsp . '\\' . 'options';
                    $pcl = new $class;
                    // 检查插件是否允许启用
                    array_push($this->listens, $pcl);
                }
            } else {
                array_push($this->errors, "插件 " . $value . " 引入失败");
            }
        }
    }

    // 取得所有插件对应页面
    public function pluginPages()
    {
        $plugins = $this->listens;
        foreach ($plugins as $key => $value) {
            if (Plugin::isOpen($plugins[$key]::NAME)) {
                if (method_exists($plugins[$key], 'onLoadPages')) {
                    $plugins[$key]->onLoadPages();
                }
            }
        }
    }

    // 加载插件需要生成的接口
    public function pluginApis()
    {
        $plugins = $this->listens;
        foreach ($plugins as $key => $value) {
            if (Plugin::isOpen($plugins[$key]::NAME)) {
                if (method_exists($plugins[$key], 'onRegisterApi')) {
                    $plugins[$key]->onRegisterApi();
                }
            }
        }
        return Register::Get('PluginApis');
    }

    // 加载插件需要生成的命令行
    public function pluginCmds()
    {
        $plugins = $this->listens;

        foreach ($plugins as $key => $value) {
            if (Plugin::isOpen($plugins[$key]::NAME)) {
                if (method_exists($plugins[$key], 'onRegisterCmd')) {
                    $plugins[$key]->onRegisterCmd();
                }
            }
        }
        return Register::Get('PluginCommand');
    }
}
