// This module is used on preview pages displayed by the UI (editor) for each block
// The standard HTML page for a block adds this module and then passes it a reference
// to its main JS module. This is used to reset the HTML page when the command is received
// from the UI.
//
// The module must have a "setConfig" function that is normally called by the HTML page.
// This code is replaced with code calling "handlePreviewMessage" and the UI passes the
// setConfig function its own version of the config data.
// As an example, if a block HTML page has code like the following in the header:
//
// <script type="module">
//     import * as config from "./drag_one_item_per_category_config.js";
//     import * as drag_into_categories from "../../_base/js/drag_one_item_per_category.js";
//     drag_into_categories.setConfig(config);
// </script>
//
// then for the preview version this would be replaced with:
//
// <script type="module">
//     import * as drag_into_categories from "../../_base/js/drag_one_item_per_category.js";
//     import {handlePreviewMessages} from "../js/handle_preview_messages.js";
//     handlePreviewMessages(drag_into_categories, "drag_into_categories");
// </script>

let blockModule;
let storageKey;
let setConfigFn;

function handlePreviewMessages({blockModule: theBlockModule, storageKey: theStorageKey, setConfigFn: theSetConfigFn}) {
    blockModule = theBlockModule ?? null;
    setConfigFn = theSetConfigFn ?? null;
    storageKey  = theStorageKey + "-config-on-reload";

    if (blockModule && !setConfigFn) {
        setConfigFn = blockModule.setConfig;
    }

    window.addEventListener("message", handleMessage);

    // If we saved a config object before reload, use that.
    let reloadConfig = localStorage.getItem(storageKey);
    if (reloadConfig !== null) {
        setConfigFn(JSON.parse(reloadConfig));
        // localStorage.removeItem(storageKey);
    }
}

function handleMessage(event) {
    console.log(`In handleMessage, event.origin = ${event.origin}`);
    console.log(`In handleMessage, event.data = ${JSON.stringify(event.data)}`);

    switch(event.data.action) {
        case "config":
            if (!setConfigFn) {
                return;
            }
            let config = event.data.actionData;
            setConfigFn(config);
            localStorage.setItem(storageKey, JSON.stringify(event.data.actionData));
            window.location.reload();
            break;

        case "goToBeginning":
            if (!storageKey) {
                return;
            }
            localStorage.setItem(storageKey, JSON.stringify(event.data.actionData));
            window.location.reload();
            break;
    }
}

export {handlePreviewMessages};