"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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.changeComponent = void 0;
const cyia_code_util_1 = require("cyia-code-util");
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
function changeComponent(data) {
    const sf = ts.createSourceFile('', data, ts.ScriptTarget.Latest, true);
    const selector = (0, cyia_code_util_1.createCssSelectorForTs)(sf);
    const ɵcmpNodeList = selector.queryAll(`BinaryExpression[left$=ɵcmp]`);
    if (!ɵcmpNodeList.length) {
        return undefined;
    }
    const changeList = [];
    for (const ɵcmpNode of ɵcmpNodeList) {
        const templateNode = selector.queryOne(ɵcmpNode, `CallExpression ObjectLiteralExpression PropertyAssignment[name=template]`);
        const initIfNode = selector.queryOne(templateNode, `IfStatement[expression="rf & 1"]`);
        if (!initIfNode) {
            continue;
        }
        const initBlock = initIfNode.thenStatement;
        const change = new cyia_code_util_1.TsChange(sf);
        const initInsertChange = change.insertNode(initBlock.statements[initBlock.statements.length - 1], `;amp.pageBind(ctx);`, 'end');
        let updateInsertChange;
        changeList.push(new cyia_code_util_1.InsertChange(0, `import * as amp from 'angular-miniprogram';\n`), initInsertChange);
        const updateIfNode = selector.queryOne(templateNode, `IfStatement[expression="rf & 2"]`);
        const updateContent = `amp.propertyChange(ctx);`;
        if (updateIfNode) {
            const updateBlock = updateIfNode.thenStatement;
            updateInsertChange = change.insertNode(updateBlock.statements[updateBlock.statements.length - 1], `;${updateContent}`, 'end');
        }
        else {
            updateInsertChange = change.insertNode(initIfNode, `if(rf & 2){${updateContent}}`, 'end');
        }
        changeList.push(updateInsertChange);
    }
    return {
        content: util_1.RawUpdater.update(data, changeList),
        // todo library可否支持同文件多组件
        componentName: ɵcmpNodeList[0].left.expression.getText(),
    };
}
exports.changeComponent = changeComponent;
