"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runHandleMaterial = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const webpack_1 = require("../service/webpack");
const copy_1 = require("./copy");
const types_1 = require("../../types");
const common_1 = require("../util/common");
async function runHandleMaterial(appBuildDir, dependencies = [], materialsDir, runtime = types_1.RUNTIME.NONE, ignoreInstall = false) {
    const normalDependencies = [];
    const compositeDependencies = [];
    dependencies.forEach((item) => {
        if (item.isComposite) {
            compositeDependencies.push(item);
        }
        else {
            normalDependencies.push(item);
        }
    });
    const allMaterials = await handleNormalMaterial({
        dependencies: normalDependencies,
        materialsDir,
        appBuildDir,
        runtime,
        ignoreInstall,
    });
    return allMaterials.concat(compositeDependencies);
    // TODO: 确认这里是否需要生成复合组件
    // await handleCompositeComponent({ dependencies, appBuildDir });
}
exports.runHandleMaterial = runHandleMaterial;
async function handleNormalMaterial({ dependencies: normalDependencies, materialsDir, appBuildDir, runtime, ignoreInstall = false, }) {
    const timeTag = '-------------------- handleNormalMaterial';
    console.time(timeTag);
    await (0, webpack_1.downloadAndInstallDependencies)(normalDependencies, materialsDir, {
        runtime,
        ignoreInstall,
    });
    await (0, copy_1.copyMaterialLibraries)(normalDependencies, materialsDir, appBuildDir);
    console.timeEnd(timeTag);
    return Promise.all(normalDependencies.map(async (metaInfo) => {
        var _a, _b, _c, _d, _e, _f;
        const materialNameVersion = `${metaInfo.name}@${metaInfo.version}`;
        const materialItemPath = path
            .resolve(appBuildDir, 'src/libraries', materialNameVersion)
            .replace(/packages\/\w+\//, ''); // HACK：去除子包的目录，找根目录的素材地址。后续提供一个方法获取这些关键路径。
        const materialComponentsPath = path.resolve(materialItemPath, `components`);
        const actionsDir = path.join(materialItemPath, 'actions');
        const meta = (0, common_1.readComponentLibMata)(materialItemPath);
        let actions = [];
        let components = [];
        let { schemaVersion, isPlainProps, entries } = metaInfo;
        try {
            const packageJson = fs.readJsonSync(path.join(materialsDir, materialNameVersion, 'package.json'));
            if ((_b = (_a = packageJson.weda) === null || _a === void 0 ? void 0 : _a.platform) === null || _b === void 0 ? void 0 : _b.web) {
                const _entries = (_d = (_c = packageJson.weda) === null || _c === void 0 ? void 0 : _c.platform) === null || _d === void 0 ? void 0 : _d.web;
                entries = {
                    entry: path.posix.join('./', _entries.entry),
                    components: path.posix.join('./', _entries.components),
                    actions: path.posix.join('./', _entries.actions),
                };
            }
            else if (packageJson.lowcode) {
                entries = {
                    entry: path.posix.join('./', packageJson.lowcode),
                };
            }
        }
        catch (e) { }
        if (meta) {
            if (meta === null || meta === void 0 ? void 0 : meta.schemaVersion) {
                schemaVersion = meta === null || meta === void 0 ? void 0 : meta.schemaVersion;
            }
            let [major] = ((_e = meta === null || meta === void 0 ? void 0 : meta.schemaVersion) === null || _e === void 0 ? void 0 : _e.split('.')) || [];
            if (Number(major) >= 3) {
                isPlainProps = true;
            }
            const { components: componentsMap, actions: actionsMap = {} } = meta;
            for (let name in componentsMap) {
                const { $schema, platforms, data, dataForm, events, emitEvents, ...rest } = componentsMap[name];
                components.push({
                    ...rest,
                    dataForm: dataForm || data.properties,
                    emitEvents: emitEvents ||
                        (events === null || events === void 0 ? void 0 : events.map((event) => {
                            return {
                                eventName: event.name,
                                name: event.title,
                            };
                        })),
                    name,
                    type: 'component',
                });
            }
            for (let name in actionsMap) {
                actions.push({ name });
            }
        }
        else {
            // 老格式，需要从子目录下读取
            actions = ((_f = fs.readdirSync(actionsDir)) === null || _f === void 0 ? void 0 : _f.map((dirName) => ({ name: dirName }))) || [];
            components = await Promise.all((fs.readdirSync(materialComponentsPath) || []).map(async (name) => {
                const componentMetaPath = `${materialComponentsPath}/${name}/meta.json`;
                let metaJson = {
                    name,
                    meta: await fs.readJson(componentMetaPath),
                };
                return metaJson;
            }));
        }
        return {
            ...metaInfo,
            schemaVersion,
            isPlainProps,
            entries,
            actions: actions.length ? actions : metaInfo.actions,
            components: components.length ? components : metaInfo.components,
            plugins: [],
        };
    }));
}
