/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define([
	    'mage/translate',
	    'Magento_Ui/js/form/element/abstract',
	    'MNM_Spitzner/js/lib/address-verification',
	    'ko',
	    'jquery',
        'Magento_Checkout/js/model/quote'], 
    function ($t, Abstract, av, ko, $, quote) 
    {
	    'use strict';
	
	    ko.bindingHandlers.addressAutoComplete = {
    	    init: function (element, valueAccessor) {
    	        var settings = valueAccessor();

    	        var options = settings.options;
    	        var minLength = settings.minLength;
    	        var selectedOption = settings.selectOption;
    	        
    	        var updateElementValueWithLabel = function (event, ui) 
    	        {
    	        	// Stop the default behavior
    	            event.preventDefault();

    	            // Update the value of the html element with the label
    	            // of the activated option in the list (ui.item)
    	            $(element).val(ui.item.value);

    	            // Update our SelectedOption observable
    	            if(typeof ui.item !== "undefined") {
    	            	selectedOption({id: $(element).attr('id'), option: ui.item});
    	            }
    	        };
 
    	        $(element).autocomplete({
    	            source: options, 
    	            select: function (event, ui) {
    	                updateElementValueWithLabel(event, ui);
    	            },
    				minLength: minLength
    	        });
    	    }
    	};
	    
	    return Abstract.extend({
	    	selectedOption: ko.observable(null),
	    	minLength: 1,
	    	
	    	initialize: function () 
	    	{
	    		this._super();
	    		
	    		this.minLength = (this.index == 'postcode') ? 3 : 1;
	    		
	    		this.selectedOption.subscribe(this.onSelectOption.bind(this));
	    	},

	    	onSelectOption: function(data) 
	    	{
	    		let option = data.option;

	    		if(data.id == this.uid)
	    		{		    		
		    		if(this.inputName == 'postcode')
	    			{
		    			this.getPostcode().keyup().change();
		    			this.getCity().val(option.city).keyup().change();
	    			}
		    		else if(this.inputName == 'street[0]')
	    			{
		    			this.getStreet().keyup().change();
		    			
		    			if(typeof option.housenumber !== 'undefined')
						{
		    				this.getHousenumber().val(option.housenumber).keyup().change().focus();
						}
						if(typeof option.postcode !== 'undefined' && this.getPostcode().val() == '')
						{
							this.getPostcode().val(option.postcode).keyup().change();
						}
						if(typeof option.city !== 'undefined' && this.getCity().val() == '')
						{
							this.getCity().val(option.city).keyup().change();
						}
						if(typeof option.type !== 'undefined')
						{
							if(option.type == 'Address')
							{
								av.AddressIdChosen = option.id;
							}
						}
	    			}
	    		}
	    	},
	    	
	    	getPostcode: function() { return $('[name="'+this.parentScope.split('.')[0]+'.postcode"] [name="postcode"]'); },
	    	getCity: function() { return $('[name="'+this.parentScope.split('.')[0]+'.city"] [name="city"]'); },
	    	getCountry: function() { return $('[name="'+this.parentScope.split('.')[0]+'.country_id"] [name="country_id"]').val();},
	    	getStreet: function() { return $('[name="'+this.parentScope.split('.')[0]+'.street.0"] [name="street[0]"]'); },
	    	getHousenumber: function() { return $('[name="'+this.parentScope.split('.')[0]+'.street.2"] [name="street[2]"]'); },
	    	
	    	getAutocompleteOptions: function(request, response) 
	    	{
	    		var vm = ko.dataFor(this.element[0]);
	    		var country = vm.getCountry();
	    		
				if(country == 'DE' || country == 'AT')
				{
					if(vm.index == 'postcode')
					{
						vm.getPostcodes(request, response, country);
					}
					else if(vm.inputName == 'street[0]')
					{
						vm.getStreets(request, response, country);
					}
				}
				else
				{
					response();
				}
	    	},
	    	
	    	getPostcodes: function(request, response, country) 
	    	{
	    		av.OpenRequests = request.term.length == 3 ? 10 : 1;

				for(var i = 0; i < av.OpenRequests; i++)
				{
					var term = request.term;
					
					if(request.term.length == 3)
					{
						term += i;
					}
					
					av.doPCARequest(term, country, response, 0);
				}
	    	},
	    	
	    	getStreets: function(request, response, country) 
	    	{
	    		var term = this.getPostcode().val()+' '+request.term;
	    		
	    		av.doPCARequest(term, country, response, 1);
	    	},
	    	
	    	onBlurEvent: function() 
	    	{
	    		if(this.inputName == 'street[0]')
    			{
	    			var country = this.getCountry();
					var streetEntered = this.value();

					if(streetEntered != 'Packstation' && (country == 'DE' || country == 'AT'))
					{
						var term = this.getPostcode().val()+' '+streetEntered;
						av.doPCARequest(term, country, streetEntered, 2, this);
					}
    			}
	    	}
	    });
	}
);
