import $ from "jquery";

import { CrossSellingPointer } from "../../others/crossSellingPointer.js";
import { RCL } from "../names.js";

/**
 * Pagination (needs to be extract as class to avoid multiple event triggers).
 */
class CrossRclPagination {
    public static readonly SELECTOR =
        "body.wp-admin.edit-php:not(.post-type-attachment) .tablenav-pages .pagination-links a";

    public static onClick(this: HTMLElement, e: JQuery.ClickEvent) {
        const href = $(this).attr("href");
        new CrossSellingPointer($(this), RCL, "pagination");

        // Still redirect after clicking a button
        ($(this) as any)
            .pointer("widget")
            .find(".button")
            .click(() => {
                // Wait a second, because browsers like Firefox cancel the dismiss request
                setTimeout(() => window.open(href, "_self"), 1000);
            });

        $(CrossRclPagination.SELECTOR).off("click", CrossRclPagination.onClick);
        e.preventDefault();
        return false;
    }

    public static bind() {
        CrossSellingPointer.isActionAvailable(RCL, "pagination") && $(this.SELECTOR).one("click", this.onClick);
    }
}

export { CrossRclPagination };
