import * as t from "@babel/types";
import { traverse } from "../traverse.js";
function isInEventFlow(path) {
    let isInEventFlow = false;
    path.traverse({
        Identifier(path) {
            if (path.node.name === "EventFlow") {
                isInEventFlow = true;
                path.stop();
            }
        },
    });
    return isInEventFlow;
}
export function deleteEntityInAst({ entityName, ast, }) {
    // remove entity from event flows;
    traverse(ast, {
        Identifier(path) {
            const eventFlowName = path.node.name;
            if (![
                "runApis",
                "cancelApis",
                "setStateVar",
                "resetStateVar",
                "controlTimer",
                "controlSlideout",
                "setComponentProperty",
                "resetComponent",
            ].includes(eventFlowName)) {
                return;
            }
            if (!isInEventFlow(path.parentPath)) {
                return;
            }
            if (eventFlowName === "runApis" || eventFlowName === "cancelApis") {
                const expression = path.parentPath.parentPath;
                if (!t.isCallExpression(expression?.node)) {
                    return;
                }
                const args = expression.get("arguments");
                if (!t.isArrayExpression(args[0]?.node)) {
                    return;
                }
                args[0].node.elements = args[0].node.elements.filter((element) => !t.isIdentifier(element) || element.name !== entityName);
                return;
            }
            else {
                const expression = path.parentPath.parentPath;
                if (!t.isCallExpression(expression?.node)) {
                    return;
                }
                const args = expression.get("arguments");
                const entityBinding = args[0];
                if (!t.isIdentifier(entityBinding.node)) {
                    return;
                }
                if (entityBinding.node.name === entityName &&
                    t.isMemberExpression(expression.node.callee)) {
                    entityBinding.replaceWith(t.identifier("undefined"));
                }
            }
        },
    });
}
//# sourceMappingURL=entities.js.map