"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = processor;
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const utils = __importStar(require("../utils/index.js"));
const c_handler_export_1 = __importDefault(require("./c-handler-export"));
const terser_1 = require("terser");
const getModule_js_1 = __importDefault(require("../build/getModule.js"));
let gamelib_modules;
let forInscript = false;
/**
 * 替换模块 import 路径
 */
async function replaceModuleImports(code, modules, targetDir, sourceDir) {
    const im = (0, c_handler_export_1.default)(code);
    if (Array.isArray(modules)) {
        const imports = im.get();
        if (imports.length < 1)
            return code;
        for (const item of modules) {
            const moduleDir = await gamelib_modules.getDir(item);
            const main = (await utils.handlerPackage(moduleDir)).main;
            const relPath = path
                .relative(path.dirname(targetDir), path.join(sourceDir, 'node_modules', path.basename(moduleDir), main))
                .split(path.sep).join('/');
            const found = imports.find((imp) => imp.ModuleName === item);
            if (found)
                im.set({
                    ModuleName: `./${relPath}`,
                    ImportItem: found.ImportItem
                });
        }
    }
    return im.generate();
}
/**
 * 处理单个文件
 */
async function processFile(filePath, modules, sourceDir, shouldMinify) {
    try {
        const ext = path.extname(filePath).slice(1);
        const code = await fs.readFile(filePath, "utf-8");
        switch (ext) {
            case 'js':
                let replaced = await replaceModuleImports(code, modules, filePath, sourceDir);
                if (shouldMinify === true) {
                    const result = await (0, terser_1.minify)(replaced);
                    if (result.code)
                        replaced = result.code;
                }
                await fs.writeFile(filePath, replaced, 'utf-8');
                break;
            case 'json':
                let re = code;
                if (shouldMinify === true) {
                    const json = utils.JSONparse(code);
                    re = JSON.stringify(json);
                    if (forInscript) {
                        await Promise.all([
                            fs.writeFile(`${filePath}.js`, `export const data=${re}`),
                            fs.rm(filePath, { recursive: true, force: true })
                        ]);
                    }
                }
                break;
            case 'map':
            case 'ts':
                await fs.rm(filePath, { recursive: true, force: true });
                break;
        }
    }
    catch (err) {
        console.log(filePath, err.message);
    }
}
/**
 * 递归遍历并处理文件
 */
async function processDir(targetDir, modules, sourceDir, baseDir, shouldMinify) {
    const stat = await fs.stat(targetDir);
    gamelib_modules = await (0, getModule_js_1.default)(baseDir);
    let inScriptTemp = false;
    if (stat.isDirectory()) {
        const files = await fs.readdir(targetDir);
        if (path.basename(targetDir) === "scripts") {
            forInscript = true;
            inScriptTemp = true;
        }
        for (const file of files) {
            await processDir(path.join(targetDir, file), modules, sourceDir, baseDir, shouldMinify);
        }
        if (forInscript && inScriptTemp)
            forInscript = false;
    }
    else if (stat.isFile()) {
        await processFile(targetDir, modules, sourceDir, shouldMinify);
    }
    else {
        console.warn(`跳过未知类型:${targetDir}`);
    }
}
async function processor(targetDir, options) {
    await processDir(targetDir, options.modules || [], options.sourceDir, options.baseDir, options.minify);
}
