import uniqid from 'uniqid';
import { showLoader, hideLoader } from '../utils/loader';
import { updateOrderSummary } from "../components/order-summary";

export function getUniqBasketSessionId() {
    return uniqid('basket-session-');
}

export function updateBasketSession() {
    const basketSessionData = {
        currentSessionId: Wick.BasketPage.sessionId,
        currentCartEntries: Wick.BasketPage.cartEntries,
    }
    localStorage.setItem('basket-session', JSON.stringify(basketSessionData));
}

export function updateBasketDataQuantity() {
    Wick.BasketData.updateCart.pickupOrderGroups[0].entries[0].quantity += 1;
}

export function addStorageCheckEvent() {
    $(window).on('storage', (e) => {
        if (isBasketSessionUpdated(e) && isCurrentIdRequireUpdate()) {
            if (!areCartEntriesEqual()) {
                showLoader(Wick.BasketPage.el.loader);
                if (!Wick.checkLocalEnv) {
                    Wick.BasketPage.updateCart(true, ...Array(3), (...args) => {
                        Wick.BasketPage.updateCartAction(...args);

                        hideLoader(Wick.BasketPage.el.loader)
                    });
                } else {
                    updateBasketDataQuantity();
                    updateOrderSummary(
                      Wick.BasketData.updateCart,
                      Wick.BasketPage.getEqualMapForUpdateCart(Wick.BasketData.updateCart)
                    );
                    Wick.BasketPage.repaintOrderItems(Wick.BasketData.updateCart, true);
                    Wick.BasketPage.getCartEntries(Wick.BasketData.updateCart);
                    setTimeout(() => hideLoader(Wick.BasketPage.el.loader), 3000);
                }
            }
        }
    });
}

function getBasketSession() {
    try {
        const basketSession = localStorage.getItem('basket-session');
        return JSON.parse(basketSession);
    } catch (error) {
        console.error('Error parsing basket-session:', error);
        return {};
    }
}

function getCurrentCartEntries() {
    return getBasketSession().currentCartEntries;
}

function areCartEntriesEqual() {
    return _.isEqual(Wick.BasketPage.cartEntries, getCurrentCartEntries());
}

function isCurrentIdRequireUpdate() {
    return getBasketSession().currentSessionId !== Wick.BasketPage.sessionId;
}

function isBasketSessionUpdated(e) {
    return e.originalEvent.key === 'basket-session';
}
