import jQuery from "jquery";
import { Graph } from "../../graph";
import ToolMenu from "./toolmenu";

export const COLLECTION_KEY = "collection";

const SELECTED_ITEMS_ID = "#selected-items";
const CLEAR_BUTTON_ID = "#clear-collection";

const DOM_LIST_ITEM = "li";

export class CollectMenu extends ToolMenu {
    constructor() {
        super();
        this.hooked = false;
    }

    hookClearButton() {
        // On button press: Notify tool about clearing and empty list
        jQuery(CLEAR_BUTTON_ID).on("click", (e) => {
            this.notifyTool(COLLECTION_KEY, undefined);
        });
    }

    afterSet(key, value) {
        if (this.hooked === false) {
            this.hookClearButton();
            this.hooked = true;
        }

        if (key === COLLECTION_KEY) {
            this.fillDomList(SELECTED_ITEMS_ID, value, this.itemListRenderer);
        }
    }

    itemListRenderer(item) {
        return (
            "<" +
            DOM_LIST_ITEM +
            ">" +
            Graph.toStr(item) +
            "</" +
            DOM_LIST_ITEM +
            ">"
        );
    }

    fillDomList(listId, items, itemRenderer) {
        var listCont = this.find(listId);
        listCont.empty();

        items.forEach((i) => listCont.append(itemRenderer(i)));
    }
}