jQuery(function ($) {
    'use strict';

    prestashop.addListener('updatedProduct', function (resp) {
        [
            "product_prices",
            "product_cover_thumbnails",
            "product_customization",
            "product_details",
            "product_variants",
            "product_discounts",
            "product_add_to_cart",
            "product_additional_info",
            "product_images_modal"
        ].forEach(function (prop) {
            var replacement = resp[prop];
            if (typeof replacement !== 'string') {
                return;
            }

            $(replacement).filter('[data-ajax-refresh]').each(function () {
                var selector = '.' + this.getAttribute('data-ajax-refresh');
                $(selector + ':not(' + selector + ' ' + selector + ')').replaceWith(this);
            });
        });
        _$(document).trigger('bd-refresh-thumbnails');
    });

    $('button[data-action="show-password"]').on('click', function () {
        var elm = $(this).closest('.input-group').children('input.js-visible-password');
        if (elm.attr('type') === 'password') {
            elm.attr('type', 'text');
            $(this).text($(this).data('textHide'));
        } else {
            elm.attr('type', 'password');
            $(this).text($(this).data('textShow'));
        }
    });

    $('body').on('click', '[data-button-action="add-to-cart"]', function () {
        prestashop.addListener('updateCart', function () {
            location.href = $('#add-to-cart-or-refresh').attr('action');
        });
    });


    /**
     * Inherited from js/cart.js
     */
    prestashop.cart = prestashop.cart || {};
    prestashop.cart.active_inputs = null;

    $(document).ready(function () {
        var productLineInCartSelector = '.js-cart-line-product-quantity';
        var promises = [];

        var $body = $('body');

        function camelize(subject) {
            var actionTypeParts = subject.split('-');
            var i;
            var part;
            var camelizedSubject = '';

            for (i = 0; i < actionTypeParts.length; i++) {
                part = actionTypeParts[i];

                if (0 !== i) {
                    part = part.substring(0, 1).toUpperCase() + part.substring(1);
                }

                camelizedSubject = camelizedSubject + part;
            }

            return camelizedSubject;
        }

        function parseCartAction($target) {
            return {
                url: $target.attr('href'),
                type: camelize($target.data('link-action'))
            }
        }

        var abortPreviousRequests = function () {
            var promise;
            while (promises.length > 0) {
                promise = promises.pop();
                promise.abort();
            }
        };

        var handleCartAction = function (event) {
            event.preventDefault();

            var $target = $(event.currentTarget);
            var dataset = event.currentTarget.dataset;

            var cartAction = parseCartAction($target, event.namespace);
            var requestData = {
                ajax: '1',
                action: 'update'
            };

            if (typeof cartAction === 'undefined') {
                return;
            }

            abortPreviousRequests();
            $.ajax({
                url: cartAction.url,
                method: 'POST',
                data: requestData,
                dataType: 'json',
                beforeSend: function (jqXHR) {
                    promises.push(jqXHR);
                }
            }).then(function (resp) {
                // Refresh cart preview
                prestashop.emit('updateCart', {
                    reason: dataset
                });
            }).fail(function (resp) {
                prestashop.emit('handleError', {
                    eventType: 'updateProductInCart',
                    resp: resp,
                    cartAction: cartAction.type
                });
            });
        };

        $body.on(
            'click',
            '[data-link-action="devare-from-cart"], [data-link-action="remove-voucher"]',
            handleCartAction
        );

        function sendUpdateQuantityInCartRequest(updateQuantityInCartUrl, requestData, $target) {
            abortPreviousRequests();

            return $.ajax({
                url: updateQuantityInCartUrl,
                method: 'POST',
                data: requestData,
                dataType: 'json',
                beforeSend: function (jqXHR) {
                    promises.push(jqXHR);
                }
            }).then(function (resp) {
                $target.val(resp.quantity);

                var dataset;
                if ($target && $target.dataset) {
                    dataset = $target.dataset;
                } else {
                    dataset = resp;
                }


                // Refresh cart preview
                prestashop.emit('updateCart', {
                    reason: dataset
                });
            }).fail(function (resp) {
                prestashop.emit('handleError', {eventType: 'updateProductQuantityInCart', resp: resp})
            });
        }

        function getRequestData(quantity) {
            return {
                ajax: '1',
                qty: Math.abs(quantity),
                action: 'update',
                op: getQuantityChangeType(quantity)
            }
        }

        function getQuantityChangeType($quantity) {
            return ($quantity > 0) ? 'up' : 'down';
        }

        function updateProductQuantityInCart(event) {
            var $target = $(event.currentTarget);
            var updateQuantityInCartUrl = $target.data('update-url');
            var baseValue = $target.attr('value');

            // There should be a valid product quantity in cart
            var targetValue = $target.val();

            if (targetValue != parseInt(targetValue) || targetValue < 0 || isNaN(targetValue)) {
                $target.val(baseValue);

                return;
            }

            // There should be a new product quantity in cart
            var qty = targetValue - baseValue;
            if (qty == 0) {
                return;
            }

            var requestData = getRequestData(qty);

            sendUpdateQuantityInCartRequest(updateQuantityInCartUrl, requestData, $target);
        }

        $body.on(
            'focusout',
            productLineInCartSelector,
            function (event) {
                updateProductQuantityInCart(event);
            }
        );

        $body.on(
            'keyup',
            productLineInCartSelector,
            function (event) {
                if (event.keyCode == 13) {
                    updateProductQuantityInCart(event);
                }
            }
        );

        $body.on(
            'click',
            '.js-discount .code',
            function (event) {
                event.stopPropagation();

                var $code = $(event.currentTarget);
                var $discountInput = $('[name=discount_name]');

                $discountInput.val($code.text());

                return false;
            }
        );
    });
});

/**
 * Inherited from js/listing.js
 */
$(document).ready(function () {
    var parseSearchUrl = function (event) {
        if (event.target.dataset.searchUrl !== undefined) {
            return event.target.dataset.searchUrl;
        }

        if ($(event.target).parent()[0].dataset.searchUrl === undefined) {
            throw new Error('Can not parse search URL');
        }

        return $(event.target).parent()[0].dataset.searchUrl;
    };

    $('body').on('change', '#search_filters input[data-search-url]', function (event) {
        prestashop.emit('updateFacets', parseSearchUrl(event));
    });

    $('body').on('click', '.js-search-filters-clear-all', function (event) {
        prestashop.emit('updateFacets', parseSearchUrl(event));
    });

    $('body').on('click', '.js-search-link', function (event) {
        event.preventDefault();
        prestashop.emit('updateFacets', $(event.target).closest('a').get(0).href);
    });

    $('body').on('change', '#search_filters select', function (event) {
        const form = $(event.target).closest('form');
        prestashop.emit('updateFacets', '?' + form.serialize());
    });

    prestashop.on('updateProductList', function (data) {
        updateProductListDOM(data);
    });
});

function updateProductListDOM(data) {
    $('#search_filters').replaceWith(data.rendered_facets);
    $('#js-active-search-filters').replaceWith(data.rendered_active_filters);
    $('#js-product-list-top').replaceWith(data.rendered_products_top);
    $('#js-product-list').replaceWith(data.rendered_products);
    $('#js-product-list-bottom').replaceWith(data.rendered_products_bottom);
}
