import { app } from "../../../scripts/app.js";

app.registerExtension({
    name: "Bjornulf.CustomStringType",
    async beforeRegisterNodeDef(nodeType, nodeData, app) {
        if (nodeData.name === "Bjornulf_WriteImageAllInOne") {
            const onNodeCreated = nodeType.prototype.onNodeCreated;
            nodeType.prototype.onNodeCreated = function () {
                onNodeCreated?.apply(this, arguments);
                const locationInput = this.inputs.find(input => input.name === "location");
                if (locationInput) {
                    locationInput.type = "CUSTOM_STRING";
                }
            };
        }
    },
    async setup(app) {
        app.registerCustomNodeType("CUSTOM_STRING", (value) => {
            return {
                type: "CustomStringType",
                data: { value: value || "" },
                name: "CustomStringType"
            };
        });
    }
});


        // Override the default onConnectionCreated method
        const originalOnConnectionCreated = LGraphCanvas.prototype.onConnectionCreated;
        LGraphCanvas.prototype.onConnectionCreated = function(connection, e, node_for_click) {
            if (node_for_click && node_for_click.type === "WriteImageAllInOne" && connection.targetInput.name === "location") {
                // Check if the connected node is not already a CustomString
                if (connection.origin_node.type !== "CustomString") {
                    // Create a new CustomString node
                    const customStringNode = LiteGraph.createNode("CustomString");
                    // Position the new node
                    customStringNode.pos = [connection.origin_node.pos[0] + 200, connection.origin_node.pos[1]];
                    this.graph.add(customStringNode);

                    // Connect the new CustomString node
                    connection.origin_node.connect(connection.origin_slot, customStringNode, 0);
                    customStringNode.connect(0, node_for_click, connection.target_slot);

                    // Remove the original connection
                    connection.origin_node.disconnectOutput(connection.origin_slot, node_for_click);
                    
                    return true; // Prevent the original connection
                }
            }
            return originalOnConnectionCreated.apply(this, arguments);
        };