import { existsSync, readFileSync, readdirSync, statSync } from "fs-extra";
const exclude = ["plugin-bridge", "plugin-editor", "plugin-test"];

function isExclude(name: string) {
    return exclude.includes(name);
}
export function getPluginConfigs() {
    const files = readdirSync(Editor.Project.path + "/extensions");
    let pluginConfigs: any = {};
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const stats = statSync(Editor.Project.path + "/extensions/" + file);
        if (stats.isDirectory() && existsSync(Editor.Project.path + "/extensions/" + file + "/package.json") && !isExclude(file)) {
            let configFile = readFileSync(Editor.Project.path + "/extensions/" + file + "/package.json", "utf-8");
            let config = JSON.parse(configFile);
            // config.path = Editor.Project.path + "/extensions/" + file;
            pluginConfigs[config.name] = config;
        }
    }
    return pluginConfigs;
}

export function getI18nConfig() {
    let pluginsi18n: any = {};
    const files = readdirSync(Editor.Project.path + "/extensions");
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const stats = statSync(Editor.Project.path + "/extensions/" + file);
        if (stats.isDirectory() && !isExclude(file) && existsSync(Editor.Project.path + "/extensions/" + file + "/package.json")) {
            // let config = require(Editor.Project.path + "/extensions/" + file + "/package.json");
            let configFile = readFileSync(Editor.Project.path + "/extensions/" + file + "/package.json", "utf-8");
            let config = JSON.parse(configFile);
            pluginsi18n[config.name] = {};
            if (existsSync(Editor.Project.path + "/extensions/" + file + "/i18n/en.js")) {
                let en = require(Editor.Project.path + "/extensions/" + file + "/i18n/" + "en.js");
                let parseJson:any = {};
                parseI18n(en, parseJson, "i18n:" + config.name);
                pluginsi18n[config.name].en = parseJson;
            }

            if (existsSync(Editor.Project.path + "/extensions/" + file + "/i18n/zh.js")) {
                let zh = require(Editor.Project.path + "/extensions/" + file + "/i18n/" + "zh.js");
                let parseJson:any = {};
                parseI18n(zh, parseJson, "i18n:" + config.name);
                pluginsi18n[config.name].zh = parseJson;
            }
        }
    }
    return pluginsi18n;
}

function parseI18n(obj: { [x: string]: any; }, parsedConfig: { [x: string]: any; }, key: any) {
    for (const k in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, k)) {
            let preKey = key ? key + "." + k : k;
            if (typeof obj[k] == "string") {
                parsedConfig[preKey] = obj[k];
            } else if (typeof obj[k] == "object") {
                parseI18n(obj[k], parsedConfig, preKey);
            }
        }
    }
}