// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['hpsum/presenter/ilofederation/iloFederationPresenter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/Notifications',
    'hp/core/Localizer',
    'hp/view/FormStateView',
    'text!hpPages/core/header_help.html',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'hp/lib/jquery.hpSearchCombo',
    'lib/jquery.selectBox'],
function(presenter,router, urlFragment, notifications, localizer, FormStateView,headerHelpHtml) { "use strict";

    var iloFederationInventoryDView = (function() {
      
        var OK = '#hpsum-node-inventory-ok';
        var CANCEL ='#hpsum-node-inventory-close';
        var PANEL_SELECTOR = '#hpsum-node-inventory-panel-selector';
        var PANELS = '#hpsum-node-inventory-panels';
        var FORM = '#hpsum-node-inventory-form';
        var TITLE = '#hpsum-ilo-federation-group'; 
        var TYPE ='#hpsum-node-type';
        var NAME = '#hpsum-node-name',
        	FAILEDMSG ='#hpsum-node-inventory-failed-details',
        	FAILEDPANEL ='#hpsum-node-inventory-failed',
        	BASELINES = '#hpsum-node-baselines-search',
        	ASSOCBASELINE = '#hpsum-node-baseline',
        	REMOVEBASELINE='#hpsum-node-baseline-remove',
        	REMOVEHOTFIX='#hpsum-node-addpackage-remove',
        	HOTFIX ='#hpsum-node-addpackage-search',
        	ASSOCHOTFIX ='#hpsum-node-addpackage';
        var ROUTE_PREFIX = '/ilofederation/inventory';
		
		var INTILO_SELECTFROMLIST ='#hpsum-ilofederation-selectfromlist',
		    INTILO_ENTERMANUALLY ='#hpsum-ilofederation-enetermanually',
			//INTILO_TYPE ='#hpsum-ilofederation-select',
			ILOFED_SELECT ='#hpsum-ilofederation-interfaceilo',
			ILOFED_SELECT_ILOS ='#hpsum-ilofed-select-ilos',
			USERNAME = '#hpsum-node-credential-username',
           	PASSWORD = '#hpsum-node-credential-password',
			USERNAME_ERR ='#hpsum-node-username-err',
			PASSWORD_ERR ='#hpsum-node-password-err',
			ILOFED_SELECT_DISCOVERED = '#hpsum-ilofed-discovered-ilo-list',
			ILOFED_SELECT_MANUAL = '#hpsum-iodfed-manual-iloip-list',
            ILOFED_SELECT_INPUT = '#hpsum-ilofed-select-ilos-input',
            ILOIP_INPUT_ERR = '#hpsum-iloip-input-error',
            ILOIP_SELECT_ERR = '#hpsum-iloip-error',
            ILOFED_NO_ILO_DISCOVERED = '#hpsum-ilofed-no-ilo-discovred';
        
        /**
         * Constructor
         */
        function iloFederationInventoryDView() {
          
            var inventoryInProgress = false;
            var formStateView = new FormStateView();
            var nodeItem=null;
            var baselines='',
    			hotfixes='',
    			knownilos=[],
    			assocBaseline=null,
    			newBaseline = null,
    			newHotFix  = null,
    			assocHotFix = null;
            var searchResults = [];
                
			function showiloSelectType(event) {
				var selectedType = $(ILOFED_SELECT).val();
				if (selectedType == "selectDiscovered") {
					$(ILOFED_SELECT_DISCOVERED).show();
					$(ILOFED_SELECT_MANUAL).hide();
                    $(ILOFED_SELECT_INPUT).removeClass("hp-error");
                    $(ILOIP_SELECT_ERR).hide();
				}
				else if (selectedType == "enterManual") {
					$(ILOFED_SELECT_MANUAL).show();
					$(ILOFED_SELECT_DISCOVERED).hide();
                    $(INTILO_ENTERMANUALLY).removeClass("hp-error");
                    $(ILOIP_INPUT_ERR).hide();
				}
			}
			
            function onItemChange(item) {
            	item = item.hapi;
                formStateView.reset();
            	if(item.sug_state.match(/inventory/i)) {
					$(CANCEL).trigger('click');
				}
				
				if (item) {
                    $(TITLE).text(item.sug_name);
                    $(NAME).text(item.sug_name);
                    $(ASSOCBASELINE).text('');
                    $(REMOVEBASELINE).hide();
                    $(ASSOCHOTFIX).text('');
                    $(REMOVEHOTFIX).hide();
                    nodeItem= item;
                    newBaseline = null;
    				newHotFix  = null;
    				if(item.hasOwnProperty("sug_interface_ilo_ip") && item.sug_interface_ilo_ip)
    					$(INTILO_ENTERMANUALLY).val(item.sug_interface_ilo_ip);
    				else
    					$(INTILO_ENTERMANUALLY).val("");
    					
                    if(item.baselines || item.sug_baselines){
                    	var tempbaselines = [];
                    	if(item.baselines)
                    		tempbaselines = item.baselines;
                    	else if(item.sug_baselines)
                    		tempbaselines = item.sug_baselines;
                    		
                    	for (var i=0; i<tempbaselines.length; i++ ){
                    		var baseline = presenter.getBaselineDetailsforId(tempbaselines[i]);
                    		if(baseline){
                    			if(baseline.name.match(/^Additional Package/i)){
                    				$(ASSOCHOTFIX).text(baseline.name);
                    				$(REMOVEHOTFIX).show();
                    				assocHotFix = baseline; 
                    			}else{
                    				$(ASSOCBASELINE).text(baseline.name );
                    				$(REMOVEBASELINE).show();
                    				assocBaseline = baseline;
                    			}
                    		}
                    	}
 					 }
 					
 					 knownilos=[];
 					 for ( i = 0; i < item.sug_known_ilos.length; i++) {
                        var obj = {
                            id : i,
                            name : item.sug_known_ilos[i]
                        };
                       	knownilos.push(obj);
                    }
                   

                    if(knownilos.length == 0){
                        $(ILOFED_SELECT_ILOS).hpSearchCombo('disable');
                        $(ILOFED_NO_ILO_DISCOVERED).show();
                        $(ILOFED_SELECT).selectBox('value', "enterManual");
                        $(ILOFED_SELECT).val("enterManual");
                        showiloSelectType("enterManual");

                    } 
                    else{
                        $(ILOFED_SELECT_ILOS).hpSearchCombo('enable');
                        $(ILOFED_NO_ILO_DISCOVERED).hide();
                    }

 				}
                else {
                    $(TITLE).text('');
                }
                if(item.sug_added_by_user.match(/yes/i)) {
                    $(ILOFED_SELECT_ILOS).hpSearchCombo('disable');
                    $(ILOFED_NO_ILO_DISCOVERED).show();
                }
                
            }
            
            function onInventoryError(errorMessage,hcode) {
                $(FAILEDPANEL).show();
                if(errorMessage){
                	$(FAILEDMSG).text(errorMessage);
                     formStateView.setMessage({
                            summary : errorMessage,
                            status : "error"
                    });
                }
                else{
                	$(FAILEDMSG).text(localizer.getString('hpsum.ilofederation.inventoryError'));
                    formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.inventoryError'),
                            status : "error"
                    });
                }

                inventoryInProgress = false;
            }

            function onInventorySuccess(item) {
                inventoryInProgress = false;
                $(CANCEL).trigger('click');
            }

			function OnResize(){
				var BaseLineSearchWidth = ($(window).width() / 3);
				$(BASELINES).hpSearchCombo({getResults:getBaseline, width:BaseLineSearchWidth});
				$(HOTFIX).hpSearchCombo({getResults: getHotfixes, width:BaseLineSearchWidth});
			}

            
            function onInventory() {
            	var fail=false;
            	var finalBaseline;
            	var finalHotFix;
            	var baselineJson=[];
                var selectedType = $(ILOFED_SELECT).val();

                nodeItem.ip = null;
                if (selectedType == "selectDiscovered") {
                    var ind = $(ILOFED_SELECT_ILOS).val();
                    if(ind)
                        nodeItem.ip = knownilos[ind].name;
                }
                else if (selectedType == "enterManual")
                    nodeItem.ip = $(INTILO_ENTERMANUALLY).val();

                if(!nodeItem.ip) {
                    if(selectedType == "selectDiscovered" && knownilos.length) {
                        $(ILOFED_SELECT_INPUT).addClass("hp-error");
                        formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.requiredFieldMissing',
                                                        [localizer.getString('hpsum.ilofederation.selectDiscovered')]),
                            status : "error"
                    });
                        $(ILOIP_SELECT_ERR).show();
                    }
                    else if (selectedType == "enterManual") {
                        $(INTILO_ENTERMANUALLY).addClass("hp-error");
                        $(ILOIP_INPUT_ERR).show();
                        formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.requiredFieldMissing',
                                                        [localizer.getString('hpsum.common.ipDns')]),
                            status : "error"
                    });
                    }
                    else {
                         formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.noIloDiscovered'),
                            status : "error"
                    });

                    }
                    return;
                }

            	
            	if($(USERNAME).val() == ''){
            		$(USERNAME).addClass("hp-error");
            		$(USERNAME_ERR).show();
                    formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.requiredFieldMissing',
                                                        [localizer.getString('hpsum.common.username')]),
                            status : "error"
                    });
            		$(USERNAME).bind('keyup', function(){
            			$(USERNAME_ERR).hide();
            			$(USERNAME).removeClass('hp-error');
            		});
            		return;
            	}
            	//QXCR1001392598: Ind:Password is mandatory in inventory but iLO allows usercreation withoutpassword
		//Since  empty password is a valid configuration in iLO, hence same is supported for ILO targets

                if (! inventoryInProgress) {
                	if((newBaseline == null) && (assocBaseline == null))
                		finalBaseline = null;
                	else if (newBaseline == null)
                		finalBaseline = assocBaseline;
                	else
                		finalBaseline = newBaseline;
                	if((newHotFix == null) && (assocHotFix == null))
                		finalHotFix = null;
                	else if (newHotFix == null)
                		finalHotFix = assocHotFix;
                	else
                		finalHotFix = newHotFix;
                		
                	if((finalHotFix == null) &&  (finalBaseline == null))
                		fail = false;
                	else if(finalHotFix == null)
                		baselineJson.push(finalBaseline.id);
                	else if (finalBaseline == null)
                		baselineJson.push(finalHotFix.id);
                	else{
                		if(finalBaseline)
                			baselineJson.push(finalBaseline.id);
                		if(finalHotFix)
                			baselineJson.push(finalHotFix.id);
                	}
                	if(fail == true){
                		$(FAILEDPANEL).show();
                		$(FAILEDMSG).text(localizer.getString('hpsum.node.errorPleaseSelectBaseline'));
                        formStateView.setMessage({
                            summary : localizer.getString('hpsum.node.errorPleaseSelectBaseline'),
                            status : "error"
                        });
                	}
                	else {
                		$(FAILEDPANEL).hide();
                		$(FAILEDMSG).text('');
                		nodeItem.baselines = baselineJson;
                		nodeItem.username = $('#hpsum-node-credential-username').val();
                		nodeItem.password = $('#hpsum-node-credential-password').val();
                    inventoryInProgress = true;
                    presenter.startInventory(nodeItem, {
                        success : onInventorySuccess,
                        error : onInventoryError
                    });
                   }
                }
            }
            
            
            function changeLocation(location) {
                if (location.length > ROUTE_PREFIX.length) {
                    $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
                } else {
                    $(PANELS).hpStackedPanels('setFirstPanel');
                }
            }
            
            this.resume = function () {
			    presenter.on('itemChange', onItemChange);
				//presenter.on('selectionChange', onSelectionChange);
                //presenter.on('searchSuggestionChange', baselinesAvailable);
	            $(HOTFIX).hpSearchCombo('set', {id:'', name: ''});
	            baselines = hotfixes = localizer.getString('hpsum.common.loading');
                 	presenter.getAllBaselines({
           					success:getBaselinesSuccess,
           					error: getBaselinesError
           			});
                $(PANELS).hpStackedPanels('resume');
                $(OK).removeAttr("disabled");
                $(FAILEDPANEL).hide();
                $(BASELINES).hpSearchCombo('set', {id:'', name: ''});
                
				$(ILOFED_SELECT).bind('change', showiloSelectType);
				$(ILOFED_SELECT_ILOS).hpSearchCombo('set', {id:'', name: ''});
                //This will hide the other input text box based on the select choice
                showiloSelectType();

				$(USERNAME).removeClass("hp-error");
            	$(PASSWORD).removeClass("hp-error");
            	$(USERNAME).val("");
            	$(PASSWORD).val("");
				$(USERNAME_ERR).hide();
				$(PASSWORD_ERR).hide();
                if(knownilos.length) {
                    $(ILOFED_SELECT).selectBox('value', "selectDiscovered");
    				$(ILOFED_SELECT).val("selectDiscovered");
    				$(ILOFED_SELECT_MANUAL).hide();
    				$(ILOFED_SELECT_DISCOVERED).show();
                }
                $(INTILO_ENTERMANUALLY).removeClass("hp-error");
                $(ILOIP_INPUT_ERR).hide();
                $(ILOFED_SELECT_INPUT).removeClass("hp-error");
                $(ILOIP_SELECT_ERR).hide();
			};
            
            this.pause = function () {
            	presenter.off('itemChange', onItemChange);
            	$(BASELINES).hpSearchCombo('set', {id:'', name: ''});
                $(HOTFIX).hpSearchCombo('set', {id:'', name: ''});
              	//presenter.off('searchSuggestionChange', baselinesAvailable);
                $(PANELS).hpStackedPanels('pause');
                $(ILOFED_SELECT_ILOS).hpSearchCombo('set', {id:'', name: ''});
                $(USERNAME_ERR).hide();
				$(PASSWORD_ERR).hide();
                $(INTILO_ENTERMANUALLY).removeClass("hp-error");
                $(ILOIP_INPUT_ERR).hide();
                $(ILOFED_SELECT_INPUT).removeClass("hp-error");
                $(ILOIP_SELECT_ERR).hide();
                formStateView.reset();
            };
          
          	function baselinesAvailable(data){
    			//data = {count: data.count, members: data};
            	//$(BASELINES).hpSearchCombo({getResults: presenter.getResults});
            }
            
            function getBaseline(string, handlers){
            	var results = baselines;
            		if (string && string.length > 0) {
              			 results =
                		    $.grep(baselines, function(option, index) {
                    		    return (option.name.match(
                  	         			 new RegExp(string.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i')));
                  		  });	
           			 }
            		handlers.success({count: results.length, members: results, start: 0, total: results.length});
        	}
            
            function getHotfixes(string, handlers){
          		  	var results = hotfixes;
            		if (string && string.length > 0) {
              			 results =
                		    $.grep(hotfixes, function(option, index) {
                    		    return (option.name.match(
                  	         			 new RegExp(string.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i')));
                  		  });	
           			 }
            		handlers.success({count: results.length, members: results, start: 0, total: results.length});
          	}
          	
          	function getKnowniLOs(string, handlers){
          		  	var results = knownilos;
          		  	
            		if (string && string.length > 0) {
              			 results =
                		    $.grep(knownilos, function(option, index) {
                    		    return (option.name.match(
                  	         			 new RegExp(string, 'i')));
                  		  });	
           			 }
            		handlers.success({count: results.length, members: results, start: 0, total: results.length});
            }
          
           function getBaselinesSuccess(searchResults)
            {
					baselines = $.grep(searchResults, function (option, index ) {
        				return !(option.name.match(new RegExp('^Additional', 'i')));
        			});
        			hotfixes = $.grep(searchResults, function (option, index) {
        				return (option.name.match(new RegExp('^Additional', 'i')));
           			});
            	
            }
            
            function getBaselinesError(msg)
            {
            	
            }
            /**
             * @public
             */
            this.init = function () {
              
				var resource = router.location().split('/');
                	resource = resource[1];
                	if(resource === 'node')
                		$(TYPE).val("Unknown");
                	else
                		$(TYPE).val(resource);
               		$('#hpsum-node-inventory-close').click(function () {
                        formStateView.reset();
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                });

                formStateView.init({
                        form : FORM,
                        routePattern : ROUTE_PREFIX + '.*',
                        autoTrack : true
                    });

                $(ILOFED_SELECT_ILOS).change(function (ev, value) {
					$(ILOIP_SELECT_ERR).hide();
                    $(ILOFED_SELECT_INPUT).removeClass("hp-error");
					if(value != "")
					{
						if(!(value in knownilos)) {
							$(ILOFED_SELECT_INPUT).val('');
						 }
					}
				 });

                $(INTILO_ENTERMANUALLY).bind('keyup', function(){
                    $(INTILO_ENTERMANUALLY).removeClass("hp-error");
                    $(ILOIP_INPUT_ERR).hide();
                });
                $(FAILEDPANEL).hide();
                   $(PANELS).hpStackedPanels({
                    	panelSelector : PANEL_SELECTOR
                	});
                
				$(REMOVEBASELINE).on('click',function(ev){
					assocBaseline=null;
					$(BASELINES).hpSearchCombo('set', {id:'', name: ''});
					$(ASSOCBASELINE).text('');
					$(REMOVEBASELINE).hide();
				});
				$(REMOVEHOTFIX).on('click',function(ev){
					assocHotFix=null;
					$(HOTFIX).hpSearchCombo('set', {id:'', name: ''});
					$(ASSOCHOTFIX).text('');
					$(REMOVEHOTFIX).hide();
				});
				$(window).on('resize', OnResize);
				//set width for baseline and additional package search box.
				OnResize();
                $(BASELINES).change(function (ev, value) {
                	var item = presenter.getBaselineDetailsforId(value);
                	if(item){
        				$(ASSOCBASELINE).text(item.name);
        				$(REMOVEBASELINE).show();
        				newBaseline = item;
        				}
        			else {
        				if(assocBaseline != null){
        					$(ASSOCBASELINE).text(assocBaseline.name);
        					$(REMOVEBASELINE).show();
        				}
        				newBaseline = null;
        			}//nodeItem.baselines = value;
					$(OK).removeAttr("disabled");
        			$(FAILEDPANEL).hide();
    			});
                $(HOTFIX).change(function (ev, value) {
                	var item = presenter.getBaselineDetailsforId(value);
                	if(item){
        				$(ASSOCHOTFIX).text(item.name);
        				$(REMOVEHOTFIX).show();
        				newHotFix = item;
        				}
        			else {
        				if(assocHotFix != null){
        				$(ASSOCHOTFIX).text(assocHotFix.name);
        				$(REMOVEHOTFIX).show();
        				}
        				newHotFix = null;
        			}
        			//nodeItem.baselines = value;
					$(OK).removeAttr("disabled");
        			$(FAILEDPANEL).hide();
    			});
                
                $(OK).on('click', function(ev) {
                    onInventory();
                    ev.preventDefault();
                });

                if ($('.hp-details-header-controls', $(FORM).parent()).length === 0) {
                    var headerHelp = $(headerHelpHtml);
                    localizer.localizeDom(headerHelp);
                    $('.hp-details-header', $(FORM).parent()).append(headerHelp);
                }

                
                $(ILOFED_SELECT_ILOS).hpSearchCombo('set', {id:'', name: ''});
                $(ILOFED_SELECT_ILOS).hpSearchCombo({getResults: getKnowniLOs});
				
				router.watch('node inventory section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
                
				
                this.resume();
            };
        }

        return new iloFederationInventoryDView();
    }());
    
    return iloFederationInventoryDView;
});
