define([
    'jquery',
    'Magento_Checkout/js/action/get-totals',
    'Magento_Checkout/js/model/totals'
], function ($, getTotals, totals) {
    'use strict';

    var mixin = {      		
/*MNM*/	interval: null,
		/**
         * @returns {void}
         */
        _initContent: function () {
            var products = $.extend({}, this.options.products);

            this.options.commonQty = 'common_qty' in products ?
                products['common_qty'] : this.options.commonQty;
            this.options.promoSku = Object.prototype.hasOwnProperty.call(products, 'triggered_products') ?
                products['promo_sku'] : this.options.promoSku;
            this.options.products = Object.prototype.hasOwnProperty.call(products, 'triggered_products') ?
                products['triggered_products'] : products;
            this._initElementsContent();
            this._initLoading();
            this._initOptions();
//MNM
            //this._initSlider();
            this.isSliderInitialized = true;
                        
            //move elements
            this.interval = setInterval(function() {
            	if($('.promo-content').length && $('.ampromo-popup-container').length)
            	{
            		$('.promo-content').empty();
	            	$('.ampromo-popup-container .ampromo-item').each(function(){
	    				$(this).detach().appendTo('.promo-content');
	    			});
	            	
	            	clearInterval(this.interval);
            	}
            }.bind(this), 100);
            
            //prevent showing
            this.initPopup = true;
//MNM            
            $('.ampromo-items-form').mage('validation');
        },
           
//MNM
		clickUpdateCartButton: function() {
			console.log('dd')
			console.log(this)
			this.interval = setInterval(function() {
            	if(!totals.isLoading())
            	{
            		$('.checkout-update-button button').click();
	            	
	            	clearInterval(this.interval);
            	}
            }.bind(this), 100);
        },
//MNM
        
        /**
         * @param {Number} index
         * @param {Element} element
         * @private
         * @returns {void}
         */
        initHandlersOneProductAdd: function (index, element) {
            var promoItem = $(element);

            if (promoItem.find('.ampromo-options .fieldset .field').length !== 0) {
                promoItem.find('.tocart').off('click').on('click', function () {
                    $('.ampromo-item.-selected').removeClass('-selected');
                    promoItem.addClass('-selected');
                });
            }
//MNM
            var formItem = $(promoItem.find('form'));
            var self = this;
            promoItem.find('[type="submit"]').on('click', function(){
            	$('.promo-content').addClass('_block-content-loading');
            	$(this).off('click');
            	
            	if(promoItem.find('[data-rule-type]').length == 1)
            	{
					if(promoItem.find('[data-rule-type]').attr('data-rule-Type') == '1')
					{
						self.promoItems.fadeToggle()
					}
					else 
					{
						promoItem.fadeToggle();
					}
				}
				else
				{
            		promoItem.fadeToggle();
            	} 
            	
            	var formData = {};
            	formItem.serializeArray().forEach(function( item ) {
            		formData[item.name] = item.value;
                });
            	
            	$.ajax({
                    type: 'POST',
                    url: self.options.formUrl,
                    data: formData,
                    success: function(data) { 
                    	let dfd = $.Deferred();
                    	dfd.done(self.clickUpdateCartButton.bind(self))
                    	getTotals([], dfd);
                    }
                });
            });
//MNM
        },
        
        /**
         * @param {JSON} response
         * @param {String} response.popup
         * @param {Object} response.products
         * @returns {void}
         * @private
         */
        _success: function (response) {
            var isReload = !_.isEmpty(this.response) &&
                this.response.popup === response.popup &&
                this.response.products['common_qty'] === response.products['common_qty'];
//MNM
            //remove loader 
            $('.promo-content').removeClass('_block-content-loading'); 
//MNM            
            if (isReload) {
                this._initLoading();

                return;
            }

            this.response = $.extend({}, response);
            this.isSliderInitialized = false;
            this.container.html(response.popup);
            this.options.products = response.products;
            this.itemsCount = this.container.children().length;
            this.hasContent = !!this.itemsCount;

            if (this.hasContent) {
                this._initContent();
                this.container.trigger('contentUpdated');
                this._calcWidthTitle();
            }

            this._toggleMessage();

            if (this.autoOpen) {
                if (!this.initPopup &&
                    this.hasContent &&
                    !this.isClose
                ) {
                    this.show();
                    this.initPopup = true;
                }

                this._trigger('init.ampopup');
            }
        },
    }
    
    return function(target) {
    	$.widget('mage.ampromoPopup', target, mixin);
    	
    	return $.mage.ampromoPopup;
    }
});
