"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/no-explicit-any */
const core_1 = require("@angular-devkit/core");
const cyia_code_util_1 = require("cyia-code-util");
const library_1 = require("../../library");
const util_1 = require("../../util");
const const_1 = require("../const");
function default_1(data, map) {
    return __awaiter(this, void 0, void 0, function* () {
        const callback = this.async();
        const selector = (0, cyia_code_util_1.createCssSelectorForTs)(data);
        const list = selector.queryAll(`PropertyAccessExpression[name=ɵɵdefineComponent]~SyntaxList ObjectLiteralExpression PropertyAssignment[name=type]::initializer`);
        if (!list.length) {
            callback(undefined, data, map);
            return;
        }
        const context = this._compilation[const_1.ExportMiniProgramAssetsPluginSymbol];
        const templateScopeOutside = this._compilation[const_1.TemplateScopeSymbol];
        const scopeLibraryObj = {};
        for (let i = 0; i < list.length; i++) {
            const element = list[i];
            const componentName = element.getText();
            const extraNode = selector.queryOne(`VariableDeclaration[name="${componentName}_${library_1.LIBRARY_COMPONENT_METADATA_SUFFIX}"]`);
            if (!extraNode) {
                continue;
            }
            const content = extraNode.initializer.getText();
            const meta = (0, util_1.literalResolve)(content);
            this._compilation[const_1.LibrarySymbol] =
                this._compilation[const_1.LibrarySymbol] || {};
            const libraryLoaderContext = this._compilation[const_1.LibrarySymbol];
            libraryLoaderContext.libraryMetaList =
                libraryLoaderContext.libraryMetaList || [];
            libraryLoaderContext.libraryMetaList.push(Object.assign(Object.assign({}, meta), { context: this.context, importPath: this.resourcePath, contextPath: this.utils.contextify(this.rootContext, this.resourcePath) }));
            const fileExtname = libraryLoaderContext.buildPlatform.fileExtname;
            libraryLoaderContext.libraryMetaList.forEach((item) => {
                const globalTemplatePath = (0, core_1.join)((0, core_1.normalize)('/library-template'), core_1.strings.classify(item.moduleId) +
                    libraryLoaderContext.buildPlatform.fileExtname.contentTemplate);
                const LIBRARY_SCOPE_ID = (0, util_1.libraryTemplateScopeName)(item.moduleId);
                const configPath = (0, core_1.join)((0, core_1.normalize)(library_1.LIBRARY_OUTPUT_ROOTDIR), item.libraryPath + fileExtname.config);
                const list = scopeLibraryObj[LIBRARY_SCOPE_ID] || [];
                list.push({
                    configPath: configPath,
                    useComponents: item.useComponents,
                    templateList: [],
                    templatePath: globalTemplatePath,
                });
                scopeLibraryObj[LIBRARY_SCOPE_ID] = list;
                const libraryTemplateLiteralConvertOptions = {
                    directivePrefix: libraryLoaderContext.buildPlatform.templateTransform.getData()
                        .directivePrefix,
                    eventListConvert: libraryLoaderContext.buildPlatform.templateTransform
                        .eventListConvert,
                    templateInterpolation: libraryLoaderContext.buildPlatform.templateTransform
                        .templateInterpolation,
                    fileExtname: libraryLoaderContext.buildPlatform.fileExtname,
                };
                this.emitFile((0, core_1.join)((0, core_1.normalize)(library_1.LIBRARY_OUTPUT_ROOTDIR), item.libraryPath + fileExtname.content), `<import src="${globalTemplatePath}"/>` +
                    (0, util_1.literalResolve)(`\`${item.content}\``, libraryTemplateLiteralConvertOptions));
                if (item.contentTemplate) {
                    this.emitFile((0, core_1.join)((0, core_1.normalize)(library_1.LIBRARY_OUTPUT_ROOTDIR), (0, core_1.dirname)((0, core_1.normalize)(item.libraryPath)), 'template' + fileExtname.contentTemplate), `<import src="${globalTemplatePath}"/>` +
                        (0, util_1.literalResolve)(`\`${item.contentTemplate}\``, libraryTemplateLiteralConvertOptions));
                }
                if (item.style) {
                    this.emitFile((0, core_1.join)((0, core_1.normalize)(library_1.LIBRARY_OUTPUT_ROOTDIR), item.libraryPath + fileExtname.style), item.style);
                }
            });
        }
        for (const key in scopeLibraryObj) {
            if (Object.prototype.hasOwnProperty.call(scopeLibraryObj, key)) {
                const element = scopeLibraryObj[key];
                templateScopeOutside.setScopeLibraryUseComponents(key, element);
            }
        }
        callback(undefined, data, map);
    });
}
exports.default = default_1;
