import $ from "jquery";
import { hooks } from "rml";

import { RootStore } from "../store/stores.js";

const REFRESH_HOOKS = [
    "rest/button/success/reset/relations",
    "rest/button/success/reset/folders",
    "folder/deleted",
    "folder/moved",
    "folder/renamed",
    "attachment/move/finished",
    "folder/meta/saved",
];

/**
 * - When the reinitialize button is successfully lets refresh the queue.
 * - Listen to schema/filelength changes for GUID / post_name
 * - Listen for automatic changes
 */
function applyOptionRestButtons() {
    const { queueStore, optionStore } = RootStore.get;
    hooks.register("rest/button/success/queue/item/potential", () => queueStore.refresh());
    hooks.register("rest/button/prepare/schema/filelength", (data: any) => {
        data.post_name = +$("#rpm_advanced_post_name").val();
        data.guid = +$("#rpm_advanced_guid").val();
    });

    // Listen for automatic changes and refresh queue
    hooks.register(REFRESH_HOOKS.join(" "), () => {
        const { isFirstTimeMoveHintDismissed, manageOptions } = optionStore.others;
        if (queueStore.canAutomaticQueueing) {
            // Automatic queueing already active, reload it
            queueStore.refresh();
        } else if (!isFirstTimeMoveHintDismissed && manageOptions) {
            // Show automatic queueing in RPM
            optionStore.setAutomaticInfoPanelOpen(true);
        }
    });
}

export { applyOptionRestButtons };
