import { noop } from "../src/core/function/noop.js";
import Editor from "./Editor.js";

/**
 *
 * @param {Engine} engine
 * @param {function(Editor):*} [initialization]
 * @returns {{enable:function, disable: function, toggle: function, editor: Editor}}
 */
export function enableEditor(engine, initialization = noop) {
    let editor = null;

    let enabled = false;

    function ensureEditor() {
        if (editor === null) {
            editor = new Editor();
            editor.engine = engine;

            editor.initialize();

            initialization(editor);
        }

        return editor;
    }

    function attachEditor() {
        if (enabled) {
            return;
        }

        console.log('Enabling editor');

        ensureEditor();

        editor.attach(engine);
        enabled = true;
    }

    function detachEditor() {
        if (!enabled) {
            return;
        }

        console.log('Disabling editor');
        if (editor !== null) {
            editor.detach();
        }
        enabled = false;
    }

    function toggleEditor() {
        if (!enabled) {
            attachEditor();
        } else {
            detachEditor();
        }

        return editor;
    }

    //bind key for toggling editor
    engine.devices.keyboard.keys.num_lock.down.add(toggleEditor);

    console.warn('Editor mode enabled, use NumLock key to toggle editor mode');

    return {
        toggle: toggleEditor,
        enable: attachEditor,
        disable: detachEditor,
        get editor() {
            ensureEditor();

            return editor;
        }
    }
}
