import { listenChanges } from "./listenChanges.js";
import { listenPanelExpanded } from "./listenPanelExpanded.js";
import { getSidebarCustomize } from "../sidebar/getSidebarCustomize.js";

/**
 * A factory functionality which provides different implementations especially
 * for the "preview" use case.
 *
 * **Note**: If you are using a store (e. g. MobX), make sure to use `setTimeout(callback, 0)`.
 * In some cases, if you do not use it, the page will result in a endless-loop.
 */
function previewFactory({
    immediateApply,
    onChange,
    onPanelChange,
}: {
    /**
     * Initially set from customize values as they can differ from sidebar values (e. g. multilingual texts).
     * You need to pass a `onChange` callback if you want to use this functionality!
     */
    immediateApply?: Parameters<typeof listenChanges>[0];
    onChange?: Parameters<typeof listenChanges>;
    onPanelChange?: Parameters<typeof listenPanelExpanded>;
}) {
    // Check if it is the sidebar customize API
    const customize = getSidebarCustomize();
    if (customize.panel) {
        if (immediateApply && onChange) {
            for (const section of Object.keys(immediateApply)) {
                const settings = immediateApply[section];
                for (const setting of Object.keys(settings)) {
                    const controlId = settings[setting];
                    onChange[1](section, setting, customize(controlId).get());
                }
            }
        }

        onChange && listenChanges(...onChange);
        onPanelChange && listenPanelExpanded(...onPanelChange);
    } else {
        console.warn("The sidebar customize API could not be retrieved!");
    }
}

export { previewFactory };
