import $ from "jquery";

async function loadFastModeContent(href: string) {
    if (process.env.PLUGIN_CTX === "pro") {
        /* onlypro:start */
        const tableFilter = $("form#posts-filter");
        const headerFilter = tableFilter.parent().children("ul.subsubsub");

        tableFilter.stop().fadeTo(250, 0.5);
        window.history.pushState({}, "", href);

        // Get the new table item rows
        const response = await $.get(href, {});
        const doc = $(response);
        const newTable = doc.find("form#posts-filter");
        const newHeader = newTable.parent().children("ul.subsubsub");
        const iep = (window as any).inlineEditPost;
        tableFilter.replaceWith(newTable);
        headerFilter.replaceWith(newHeader);

        /**
         * ported from inline-edit-post.js
         */
        iep.init();

        const qeRow = $("#inline-edit");
        const bulkRow = $("#bulk-edit");
        iep.type = $("table.widefat").hasClass("pages") ? "page" : "post";
        iep.what = "#post-";

        // prepare the edit rows
        qeRow.keyup((e) => {
            if (e.which === 27) {
                return iep.revert();
            }
        });
        bulkRow.keyup((e) => {
            if (e.which === 27) {
                return iep.revert();
            }
        });

        $(".cancel", qeRow).click(() => iep.revert());
        $(".save", qeRow).click(function () {
            return iep.save(this);
        });
        $("td", qeRow).keydown(function (e) {
            if (e.which === 13 && !$(e.target).hasClass("cancel")) {
                return iep.save(this);
            }
        });

        $(".cancel", bulkRow).click(() => iep.revert());

        $('#inline-edit .inline-edit-private input[value="private"]').click(function () {
            const pw = $("input.inline-edit-password-input");
            if ($(this).prop("checked")) {
                pw.val("").prop("disabled", true);
            } else {
                pw.prop("disabled", false);
            }
        });

        // add events
        $("#the-list").on("click", "a.editinline", function (e) {
            e.preventDefault();
            iep.edit(this);
        });

        $('select[name="_status"] option[value="future"]', bulkRow).remove();

        $("#doaction, #doaction2").click(function (e) {
            iep.whichBulkButtonId = $(this).attr("id");
            const n = iep.whichBulkButtonId.substr(2);

            if ("edit" === $(`select[name="${n}"]`).val()) {
                e.preventDefault();
                iep.setBulk();
            } else if ($("form#posts-filter tr.inline-editor").length > 0) {
                iep.revert();
            }
        });

        return true;
        /* onlypro:end */
    }
    return false;
}

export { loadFastModeContent };
