window.addEventListener('beforeunload', event => {
    if (document.iframeOrigin) {
        window.parent.postMessage(
            {
                type: 'iframe_beforeunload',
            }, document.iframeOrigin
        );
    }
});

window.addEventListener('message', event => {
    if (
        !event.origin.startsWith('myvetshop://')
        && !event.origin.startsWith('file://')
        && !event.origin.startsWith('https://localhost')
    ) {
        return;
    }
    document.iframeOrigin = event.origin;

    if ( typeof event.data.type === 'string') {
        switch (event.data.type) {
            case "get_cart_quantity":
                window.parent.postMessage(
                    {
                        type: 'iframe_cart_quantity',
                        quantity: `${prestashop.cart.products_count}`
                    }, event.origin
                );
                break;

            case "get_content_height":
                window.parent.postMessage(
                    {
                        type: 'iframe_content_height',
                        height: document.body.offsetHeight
                    }, event.origin
                );
                break;

            case 'iframe_infos':
                console.log('iframe_infos', event.data);
                window.iframeScrollTop = event.data.scroll;
                window.iframeHeight = event.data.height;
                break;
        }
    }
});
window.getMobileAppCartQuantity = function() {
    return `${prestashop.cart.products_count}`;
}

if (typeof prestashop !== 'undefined') {
    prestashop.on(
        'updateCart',
        function () {
            if (window.parent) {
                window.parent.postMessage(
                    {
                        type: 'iframe_cart_quantity',
                        quantity: `${prestashop.cart.products_count}`
                    },
                    '*'
                );
            }
        }
    );
}
