<?php

namespace Plugin\LyMaster\plugin;

use APP\program\admin\Setting;
use APP\program\admin\user\Notification;
use APP\program\Resource;
use Exception;
use LyApi\core\design\Register;
use LyApi\tools\Template;

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

class Processor
{

    // 插件后台配置
    public $admin_name = "";
    public $admin_icon = "";

    // 插件注册单个后台页面
    public function registerSP($plugin, $options)
    {
        if (gettype($plugin) == 'object' && gettype($options) == 'array') {

            $db_connect = Setting::dbConnect();
            if ($db_connect->has('plugin', ['name' => $plugin::NAME])) {
                $pid = $db_connect->get('plugin', 'id', ['name' => $plugin::NAME]);
            } else {
                throw new Exception('未注册的插件被加载！');
            }

            $title = '控制台';
            $icon = 'fa fa-cog';
            $context = "<h2>Welcome Plugin " . $plugin::NAME . "'s Center</h2>";

            if (array_key_exists('title', $options)) {
                $title = $options['title'];
            }

            if (array_key_exists('icon', $options)) {
                $icon = $options['icon'];
            }

            if (array_key_exists('context', $options)) {
                $context = $options['context'];
            }

            $pages = Register::Get('AdminPages');

            $pcontext = Register::Get('PageContext');
            if ($pcontext != '') {
                if (array_key_exists($pid, $pcontext)) {
                    $pcontext[$pid][$title] = $context;
                } else {
                    $pcontext[$pid] = '';
                    $pcontext[$pid][$title] = $context;
                }
            } else {
                $pcontext = [$pid => [$title => $context]];
            }

            Register::Set('PageContext', $pcontext);

            $arr = [
                'title' => $title,
                'icon' => $icon,
                'href' => '/admin/plugin/pages?pid=' . $pid . '&title=' . $title,
                'target' => '_self'
            ];

            if ($pages != '') {
                $now_plugin_page = $pages[$plugin::NAME];
                array_push($now_plugin_page, $arr);
                $pages[$plugin::NAME] = $now_plugin_page;
                Register::Set('AdminPages', $pages);
            } else {
                Register::Set('AdminPages', [
                    $plugin::NAME => [$arr]
                ]);
            }
        }
    }

    // 注册单个接口到系统
    public function registerAPI($func, $options, $backval = [])
    {
        if (gettype($func) == 'object' && gettype($options) == 'array') {
            $apis = Register::Get('PluginApis');

            // options 数据处理
            if (array_key_exists('type', $options)) {
                if (strtoupper($options['type']) == 'VIEW') {
                    $options['_namspace'] = 'APP\api\root';
                    $options['_function'] = 'admin';
                } else {
                    $options['_namspace'] = 'APP\api\admin\plugin';
                    $options['_function'] = '__page';
                }
            } else {
                // 自动转发到接口程序
                $options['_namspace'] = 'APP\api\admin\plugin';
                $options['_function'] = '__page';
            }

            $data = [
                "function" => $func,
                "options" => $options,
                "backval" => $backval
            ];

            if ($apis == '') {
                Register::Set('PluginApis', [$data]);
            } else {
                array_push($apis, $data);
                Register::Set('PluginApis', $apis);
            }
        } else {
            throw new Exception('非法参数类型');
        }
    }

    // 申请接管主页面
    public function applyIndexPage($self)
    {
        $cute = Setting::localDB('plugin');
        $db_connect = Setting::dbConnect();
        $sign = $db_connect->get('plugin', 'sign', ['name' => $self]);
        $nowidx = $cute->get('index_control');
        if ($nowidx == false || $nowidx != $sign) {
            $resource = new Resource();
            Notification::sendMessage(
                Template::RenderTemplate(
                    file_get_contents(LyApi . '/admin/pages/applyIndex.html'),
                    ['plugin' => $self, 'domain' => $resource->Domain(), 'layid' => '{{layid}}']
                ),
                $self,
                'info',
                '插件「' . $self . '」请求接管主页面!',
                1
            );
        }
    }

    // 注册命令行程序
    public function registerCommand($keyword, $func, $options = [])
    {
        $keywords = [];
        if (gettype($keyword) == 'string') {
            $keywords = [$keyword];
        } else if (gettype($keyword) == 'array') {
            $keywords = $keyword;
        } else {
            throw new Exception('非法参数类型');
        }

        if (gettype($func) != 'object' || gettype($options) != 'array') {
            throw new Exception('非法参数类型');
        }

        $data = [
            "function" => $func,
            "keywords" => $keywords,
            "options" => $options
        ];

        $cmds = Register::Get('PluginCommand');
        if ($cmds == '') {
            Register::Set('PluginCommand', [$data]);
        } else {
            array_push($cmds, $data);
            Register::Set('PluginCommand', $cmds);
        }
    }

    // 取得 Medoo 连接
    public function dbConnect()
    {
        return Setting::dbConnect();
    }

    // 关闭插件自身
    public function closeSelf($name)
    {

        $db_connect = Setting::dbConnect();
        if ($db_connect->has('plugin', ['name' => $name])) {
            $pid = $db_connect->get('plugin', 'id', ['name' => $name]);
        } else {
            return false;
        }

        if ($db_connect->has('plugin', ['id' => $pid])) {
            $db_connect->update('plugin', [
                'status' => '0'
            ], ['id' => $pid]);
            return true;
        }
        return false;
    }
}
