/*
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2014 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

$(document).ready(function(){
	PdProductAttributesList.initFancyboxOnProductImages();
	PdProductAttributesList.initTouchSpinOnProductQtyInputs();
	PdProductAttributesList.initEventAddToCartToButtons();

	$("#pdproductattributeslist table.table").tablesorter({
		theme : 'default',
		headerTemplate : '{content} {icon}',
		widgets : [ "uitheme", "columns" ],
	});

	prestashop.on('updateProductList', function(params) {
		if (typeof(params) !== 'undefined') {
			PdProductAttributesList.initFancyboxOnProductImages();
			PdProductAttributesList.initTouchSpinOnProductQtyInputs();
			PdProductAttributesList.initEventAddToCartToButtons();
		}
	});
});


let PdProductAttributesList = {
	initFancyboxOnProductImages(){
		if (!!$.prototype.fancybox) {
			$('.option_image a.fancybox').fancybox({
				'hideOnContentClick': true,
				'openEffect' : 'elastic',
				'closeEffect' : 'elastic',
				'helpers' : {
						overlay: {
						locked: false
					}
				}
			});
		}
	},
	initTouchSpinOnProductQtyInputs(){
		if (!!$.prototype.TouchSpin) {
			var max = parseInt($("#pdproductattributeslist input[name='qty']").data('max'));
			$("#pdproductattributeslist input[name='qty']").TouchSpin({
				min: 0,
				max: max,
				step: 1,
				decimals: 0,
				verticalbuttons: true,
				verticaldownclass: 'fa fa-minus touchspin-down bootstrap-touchspin-down material-icons touchspin-down',
				verticalupclass: 'fa fa-plus touchspin-up bootstrap-touchspin-up material-icons touchspin-up',
				buttondown_class: 'btn btn-touchspin js-touchspin  ',
				buttonup_class: 'btn btn-touchspin js-touchspin  '
			});

			$("#pdproductattributeslist_grid input[name='qty']").TouchSpin({
				min: 0,
				max: 9999999999,
				step: 1,
				decimals: 0,
				verticalbuttons: true,
				verticaldownclass: 'fa fa-minus touchspin-down bootstrap-touchspin-down material-icons touchspin-down',
				verticalupclass: 'fa fa-plus touchspin-up bootstrap-touchspin-up material-icons touchspin-up',
				buttondown_class: 'btn btn-touchspin js-touchspin  ',
				buttonup_class: 'btn btn-touchspin js-touchspin  '
			});
		}
	},
	executeAddProductsToCart(products) {
        $.ajax({
                type: 'POST',
                url: pdproductattributeslist_ajax_link,
                dataType: "json",
                data: {
                    'action': 'addProductsToCart',
                    'products': products,
                    'secure_key': pdproductattributeslist_secure_key,
                    'ajax': 1
                },
                success: function(resp) {
                    if (resp) {
                        prestashop.emit('updateCart', {
                            reason: {
                                cart: []
                            },
                            resp: resp
                        });

                        Object.entries(resp).forEach(([k, v]) => {
                        	if (v.response) {
                        		if (v.id_product_attribute > 0) {
                        			message_ok = pdproductattributeslist_product + '<b> ' + v.product_name + '</b>, ' + pdproductattributeslist_variant + ' <b> ' + v.combination_name + ' </b>' + pdproductattributeslist_add_ok;
                        			$.growl({ title: pdproductattributeslist_title_ok, message: message_ok, duration: 7000});
                        		} else {
                        			message_ok = pdproductattributeslist_product + '<b> ' + v.product_name + '</b>, ' + pdproductattributeslist_add_ok;
                        			$.growl({ title: pdproductattributeslist_title_ok, message: message_ok, duration: 7000});
                        		}

                        	} else if (v.response == false) {
                        		if (v.id_product_attribute > 0) {
                        			message_error = pdproductattributeslist_product + '<b> ' + v.product_name + '</b>, ' + pdproductattributeslist_variant + ' <b> ' + v.combination_name +'</b>, ' + pdproductattributeslist_max_qty + ' <b>' + v.max_quantity + '</b> ' + pdproductattributeslist_pcs;
                        			$.growl.error({ title: pdproductattributeslist_title_error, message: message_error, duration: 15000});
                        		} else {
                        			message_error = pdproductattributeslist_product + '<b> ' + v.product_name + '</b>, ' + pdproductattributeslist_max_qty + ' <b>' + v.max_quantity + '</b> ' + pdproductattributeslist_pcs;
                        			$.growl.error({ title: pdproductattributeslist_title_error, message: message_error, duration: 15000});
                        		}
                        	}
                        });

                    } else {
                    	$.growl.error({ title: pdproductattributeslist_title_error, message: pdproductattributeslist_add_error, duration: 15000});
                    }
                }
        });
    },
    initEventAddToCartToButtons() {
        $('body').on('click', 'button.add-to-cart-pdproductattributeslist', function(){
        	var products_array = [];
        	var tr_colection = $(this).parent().parent().parent().find('tr');
        	$(tr_colection).each(function(index) {
        		elem = $(this).find('td.option_gty');
        		qty = parseInt(elem.find('input.quantity').val());
        		if (elem.length > 0 && qty > 0) {
	        		var product = {
	                    'id_product': parseInt(elem.data('id-product')),
	                    'id_product_attribute': parseInt(elem.data('id-product-attribute')),
	                    'quantity': qty,
	                    'id_customization': 0
	                };
	                products_array.push(product);
	            }
        	});
	        if (products_array.length > 0) {
	        	PdProductAttributesList.executeAddProductsToCart(products_array);
	        } else {
	        	$.growl.error({ title: pdproductattributeslist_title_error, message: pdproductattributeslist_add_error});
	        }
       	});
    }
};