define([
	'Magento_Checkout/js/model/shipping-service',
    'Amasty_CheckoutCore/js/model/shipping-registry', 
	'Amasty_CheckoutCore/js/model/payment/payment-loading',
	'Magento_Customer/js/model/customer',
	'uiRegistry',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/address-converter',
    'underscore',
    'Magento_Checkout/js/action/select-shipping-address',
    'mage/translate',
    'jquery',
    'ko'
	],
    function (
    		shippingService, 
    		shippingRegistry, 
    		paymentLoader, 
    		customer, 
    		registry, 
    		quote, 
    		addressConverter, 
    		_, 
    		selectShippingAddress, 
    		$t, 
    		$,
    		ko) {
        'use strict';

        var mixin = {
        	isBillingSameAsShipping: ko.observable(true),
        	isShippingSameAsBilling: ko.observable(true),
        	showShippingAddressVal: false,
        		
	        initObservable: function () {
	            this._super()
	                .observe({
	                	isShippingSameAsBilling: true
	                });
	            
	            return this;
	        },
	        
	        showShippingAddress: function() {
	        	if(!this.showShippingAddressVal)
	        	{
	        		$('.amcheckout-column').addClass('addStep');
	        	}
	        	else
        		{
	        		$('.amcheckout-column').removeClass('addStep');
        		}
	        	
	        	this.showShippingAddressVal = !this.showShippingAddressVal;
	        	
	        	return true;
	        },
	        
	        /**
	         * @return {Boolean}
	         */
	        validateShippingInformation: function () {
	            var shippingAddress,
	                addressData,
	                loginFormSelector = 'form[data-role=email-with-possible-login]',
	                emailValidationResult = customer.isLoggedIn(),
	                field,
	                country = registry.get(this.parentName + '.shippingAddress.shipping-address-fieldset.country_id'),
	                countryIndexedOptions = country.indexedOptions,
	                option = countryIndexedOptions[quote.shippingAddress().countryId],
	                messageContainer = registry.get('checkout.errors').messageContainer;

	            if (!quote.shippingMethod()) {
	                this.errorValidationMessage(
	                    $t('The shipping method is missing. Select the shipping method and try again.')
	                );

	                return false;
	            }

	            if (!customer.isLoggedIn()) {
	                $(loginFormSelector).validation();
	                emailValidationResult = Boolean($(loginFormSelector + ' input[name=username]').valid());
	            }

	            if (this.isFormInline) {
	                this.source.set('params.invalid', false);
	                this.triggerShippingDataValidateEvent();

	                if (emailValidationResult &&
	                    this.source.get('params.invalid') ||
	                    !quote.shippingMethod()['method_code'] ||
	                    !quote.shippingMethod()['carrier_code']
	                ) {
	                    this.focusInvalid();

	                    return false;
	                }

	                shippingAddress = quote.shippingAddress();
	                
//MNM --> prevent loosing of housenumber
	                let shipAdr = this.source.get('shippingAddress');
	                let housenumber = ''; 
	                	
	                //retrieve from input
	                if(this.isShippingSameAsBilling())
                	{
	                	housenumber = $('div[name="billingAddressshared.street.2"] input[name="street[2]"]').val();
                	}
	                else
                	{
	                	housenumber = $('div[name="shippingAddress.street.2"] input[name="street[2]"]').val();
                	}
	                
					if(housenumber != '')
					{
	                	shipAdr.street['2'] = housenumber;
					}
	                
	                //push back
	                this.source.set('shippingAddress', shipAdr);
	                
	                addressData = addressConverter.formAddressDataToQuoteAddress(shipAdr);
//MNM <--

	                //Copy form data to quote shipping address object
	                for (field in addressData) {
	                    if (addressData.hasOwnProperty(field) &&  //eslint-disable-line max-depth
	                        shippingAddress.hasOwnProperty(field) &&
	                        typeof addressData[field] != 'function' &&
	                        _.isEqual(shippingAddress[field], addressData[field])
	                    ) {
	                        shippingAddress[field] = addressData[field];
	                    } else if (typeof addressData[field] != 'function' &&
	                        !_.isEqual(shippingAddress[field], addressData[field])) {
	                        shippingAddress = addressData;
	                        break;
	                    }
	                }

	                if (customer.isLoggedIn()) {
	                    shippingAddress['save_in_address_book'] = 1;
	                }
	                selectShippingAddress(shippingAddress);
	            } else if (customer.isLoggedIn() &&
	                option &&
	                option['is_region_required'] &&
	                !quote.shippingAddress().region
	            ) {
	                messageContainer.addErrorMessage({
	                    message: $t('Please specify a regionId in shipping address.')
	                });

	                return false;
	            }

	            if (!emailValidationResult) {
//MNM	                $(loginFormSelector + ' input[name=username]').focus();

	                return false;
	            }

	            return true;
	        }
        };
        
        return function (target) {
            return target.extend(mixin);
		}
    }
);
