import $ from "jquery";
import rmlOpts from "rmlopts";

import { addUrlParam, hooks, urlParam } from "../util/index.js";

const ID_NONE = -2;
const ID_LAST_QUERIED = -3;

function adjustLinks(df = getDefaultFolder(false)) {
    if (process.env.PLUGIN_CTX === "pro") {
        /* onlypro:start */
        $('#menu-media a[href^="upload.php"]').each(function () {
            const url = addUrlParam($(this).attr("href"), "rml_folder", df);
            $(this).attr("href", url);
        });
        /* onlypro:end */
    }
}

/**
 * Get the default folder and resolve if for example "Last queried folder".
 *
 * @param {boolean} [resolve=true] If false the rmlOpts.others.defaultFolder is returned in raw, so -2 is possible for example
 * @returns {number}
 */
function getDefaultFolder(resolve = true) {
    let id;
    if (process.env.PLUGIN_CTX === "pro") {
        /* onlypro:start */
        id = +rmlOpts.others.defaultFolder;

        // Always resolve lastQueried folder
        if (id === ID_LAST_QUERIED) {
            id = rmlOpts.others.lastQueried;
        }

        if (!resolve) {
            return id;
        }
        /* onlypro:end */
    }

    // Higher priority list mode query parameter
    id = urlParam("rml_folder") || id;

    // Resolve
    switch (id) {
        case ID_LAST_QUERIED:
            return +rmlOpts.others.lastQueried;
        default:
            return id;
    }
}

if (process.env.PLUGIN_CTX === "pro") {
    /* onlypro:start */
    /**
     * Check for changes of the default startup folder and reload the link.
     */
    hooks.register("folder/meta/saved", (id, { lastQueried }, { defaultFolder }) => {
        if (id === "usersettings") {
            rmlOpts.others.defaultFolder = defaultFolder;
            rmlOpts.others.lastQueried = lastQueried;
            adjustLinks();
        }
    });

    /**
     * Check when folder got selected save it as lastQueried.
     */
    hooks.register("tree/select", (id) => {
        rmlOpts.others.lastQueried = id;
        adjustLinks();
    });

    // Change it once
    adjustLinks();
    /* onlypro:end */
}

export { ID_NONE, ID_LAST_QUERIED, getDefaultFolder };
