import Tool from "./tool";
import * as Graph from "../graph";
import ConnectIcon from "../../images/tools/connect.png";
import { Editor } from "../components/editor";

const KEEP_SOURCE_KEY_ID = 17;

export default class ConnectTool extends Tool {
    constructor(key) {
        super("Connect two nodes", ConnectIcon, key);
        this.keepSource = false;
    }

    onNodeClick(node) {
        // Is a first node selected?
        if (
            Editor.globalState.selectedItem === undefined ||
            Editor.globalState.selectedItem.node === false
        ) {
            Editor.globalState.setSelectedItem(node);
            return;
        }

        // Add new link
        var details = {};

        var link = Editor.globalGraph.addLink(
            Editor.globalState.selectedItem[Graph.NODE_ID],
            node[Graph.NODE_ID],
            details
        );

        if (link === undefined) {
            console.error("Could not create new link");
            return;
        }

        if (this.keepSource === false) {
            // Deselect the current first node
            // TODO: Returned object not yet converted to normal one
            Editor.globalState.setSelectedItem(link);
        }
    }

    onBackgroundClick(event, positions) {
        Editor.globalState.setSelectedItem(undefined);
    }

    onKeyDown(key) {
        if (key.keyCode === KEEP_SOURCE_KEY_ID) {
            this.keepSource = true;
        }
    }

    onKeyUp(key) {
        if (key.keyCode === KEEP_SOURCE_KEY_ID) {
            this.keepSource = false;
        }
    }
}