"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.codegen = void 0;
const tslib_1 = require("tslib");
const path_1 = tslib_1.__importDefault(require("path"));
const fs_1 = tslib_1.__importDefault(require("fs"));
const core_1 = require("@il2js/core");
const Targets_1 = require("./Targets");
const TypeRegistry_1 = require("./TypeRegistry");
const OptimizeTypes_1 = require("./OptimizeTypes");
const defaultCodegenApi = {
    writeFile(filePath, data) {
        return fs_1.default.promises.writeFile(filePath, data, 'utf8');
    },
};
async function codegen({ gasm, output, targets, types, force, progressCallback, api, optimize, }) {
    const outputFile = path_1.default.join(output.outputDir, output.entry);
    if (gasm.cached && fs_1.default.existsSync(outputFile) && !force) {
        console.log(`Re-using entry ${outputFile}`);
        return;
    }
    await gasm.load();
    if (optimize) {
        OptimizeTypes_1.optimizeTypes(gasm.structs);
    }
    const typeRegistry = new TypeRegistry_1.TypeRegistry();
    const typeList = types !== null && types !== void 0 ? types : ['@il2js/core'];
    for (const entry of typeList) {
        if (typeof entry === 'string') {
            // eslint-disable-next-line import/no-dynamic-require, global-require
            const { typeExport } = require(entry);
            typeRegistry.addTypes({ from: entry, types: typeExport });
        }
        else {
            typeRegistry.addTypes(entry);
        }
    }
    for (const [targetName, targetOpts] of Object.values(targets)) {
        const Target = Object.values(Targets_1.Targets).find((target) => target.targetName === targetName);
        core_1.assert(Target, RangeError);
        const target = new Target(path_1.default.basename(gasm.gameAssemblyDllPath), gasm.version, typeRegistry, api !== null && api !== void 0 ? api : defaultCodegenApi);
        // eslint-disable-next-line no-await-in-loop
        await target.process(gasm.structs, targetOpts, progressCallback);
        // eslint-disable-next-line no-await-in-loop
        await target.write(output);
    }
}
exports.codegen = codegen;
//# sourceMappingURL=Codegen.js.map