export class PixelioCartAbandonRecoveryMoreAddToCartHandler {
    ADD_PRODUCT = "add_product";

    ISCURRENTLYADDINGPRODUCT = "1";
    ISNOTCURRENTLYADDINGPRODUCT = "0";

    CONSENTACTION = "pixelio_cart_abandon_recovery_more_is_consent_gived";

    constructor(ajaxRequest, eventTracker, emailCapture, cartTimer) {
        this.ajaxRequest = ajaxRequest;
        this.eventTracker = eventTracker;
        this.emailCapture = emailCapture;
        this.cartTimer = cartTimer;
    }

    handle($button) {
        if (!this.checkVariation($button)) {
            return false;
        }

        this.eventTracker.track("add_to_cart");

        this.checkConsent();
        this.cartTimer.pixelioCartAbandonRecoveryMoreSetRemaining();
        this.setToAddingProduct();

        return true;
    }

    showPopupAfterAddingInCart() {
        if (localStorage.getItem(this.ADD_PRODUCT) !== this.ISCURRENTLYADDINGPRODUCT) {
            return;
        }

        this.setToNotAddingProduct();
        this.emailCapture.pixelioCartAbandonRecoveryMoreShow();
    }

    checkVariation($button) {
        const $variationForm = $button.closest(".variations_form");

        if (!$variationForm.length) {
            return true;
        }

        const variationId = $button.data("variation_id");

        return variationId && variationId !== "0";
    }

    checkConsent() {
        this.ajaxRequest.makeAjaxRequest(
            this.CONSENTACTION,
            new FormData(),
            this.emailCapture.pixelioCartAbandonRecoveryMoreConsentGived,
            this.emailCapture.pixelioCartAbandonRecoveryMoreDeclinedConsent
        );
    }

    setToAddingProduct() {
        localStorage.setItem(this.ADD_PRODUCT, this.ISCURRENTLYADDINGPRODUCT);
    }

    setToNotAddingProduct() {
        localStorage.setItem(this.ADD_PRODUCT, this.ISNOTCURRENTLYADDINGPRODUCT);
    }

    isAddToCartButton($button) {
        return $button.hasClass("add_to_cart_button") ||
            $button.hasClass("pixelio-add-to-cart-button") ||
            $button.hasClass("single_add_to_cart_button");
    }
}