"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handle$comp = exports.handle$page = exports.writeCode2file = void 0;
const path_1 = __importDefault(require("path"));
const weapps_core_1 = require("@cloudbase/lowcode-generator/lib/weapps-core");
const style_1 = require("@cloudbase/lowcode-generator/lib/generator/util/style");
const generateFiles_1 = require("../util/generateFiles");
const cals_1 = require("@cloudbase/cals");
async function writeCode2file(ctx, mod, lowcodeRootDir, opts = {}, themeCode) {
    const { pageId = 'global', appDir, comp } = opts;
    const file = path_1.default.join(lowcodeRootDir, (0, weapps_core_1.getCodeModuleFilePath)(pageId || 'global', mod, { style: '.wxss' }));
    let { code } = mod;
    if (mod.type !== cals_1.ECodeType.STYLE && mod.type !== cals_1.ECodeType.THEME) {
        if (appDir) {
            // Generate app lowcode
            const baseDir = path_1.default.relative(path_1.default.dirname(file), appDir).replace(/\\/g, '/');
            // 子包混合模式需要添加相对索引到根目录
            const relativeRoot = (ctx === null || ctx === void 0 ? void 0 : ctx.isMixMode) && ctx.rootPath ? `${path_1.default.relative(`packages/${ctx.rootPath}`, '')}/` : '';
            let weappsApiPrefix = [
                `import { app, $app${pageId !== 'global' ? '' : ', $w'} } from '${relativeRoot}${baseDir}/app/weapps-api';`,
            ]; // windows compatibility
            if (pageId !== 'global') {
                weappsApiPrefix.push(`import { $page, $w } from '${baseDir}/pages/${pageId}/api';`);
            }
            code = `${weappsApiPrefix.join('\n')}\n${code}`;
        }
        else {
            // Generate component lowcode
            code = `import { app, $app, $w } from '${mod.type === 'handler-fn' ? '../' : ''}../../../../app/weapps-api';\n${code.replace(/\$comp/g, weapps_core_1.COMPONENT_API_PREFIX)}`;
        }
    }
    else {
        code = `${themeCode ? themeCode : ''}\n${code}`;
        if (comp) {
            // Add wrapper class for composited component
            code = `.${(0, weapps_core_1.getCompositedComponentClass)(comp)} {\n${code}\n}`;
        }
        try {
            code = await (0, style_1.processMpLess)(`${code}`, ctx.processCssUnit);
        }
        catch (e) {
            console.error('processLess Error', e);
        }
    }
    if (pageId) {
        // code = handle$page(code);
    }
    await (0, generateFiles_1.writeFile)(file, code);
}
exports.writeCode2file = writeCode2file;
function handle$page(code) {
    return code.replace(/\$page\b/g, 'this');
}
exports.handle$page = handle$page;
function handle$comp(code) {
    return code.replace(/\$comp\b/g, 'this');
}
exports.handle$comp = handle$comp;
