// (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',
        'jquery',
        'hp/lib/jquery.hpStackedPanels',
        'hp/lib/jquery.hpSearchCombo',
        'lib/jquery.selectBox'],
function(presenter,router, urlFragment, notifications, localizer, FormStateView) { "use strict";

    var iloFederationEditView = (function() {

        var FAILEDMSG ='#hpsum-sug-edit-failed-details',
            FAILEDPANEL ='#hpsum-sug-edit-inventory-failed',
            OK = '#hpsum-ilofederation-edit-ok',
            CANCEL ='#hpsum-ilofederation-edit-close',
            PANEL_SELECTOR = '#hpsum-sug-edit-panel-selector',
            PANELS = '#hpsum-sug-edit-panels',
            BASELINES = '#hpsum-sug-edit-baselines-search',
            HOTFIX=  '#hpsum-sug-edit-hotfix-search',
            GROUPNAME = '#hpsum-ilofed-group-name',
            GROUPDESCR = '#hpsum-ilofed-group-descr',
            INTERFACEILO = '#hpsum-ilofed-edit-interfaceilo',
            CURRENT_BASELINE = '#hpsum-ilofed-edit-baseline',
            CURRENT_HOTFIX = '#hpsum-ilofed-edit-addpackage',
            USERNAME = '#hpsum-sug-edit-credential-username',
            PASSWORD = '#hpsum-sug-edit-credential-password',
            USERNAME_ERR ='#hpsum-sug-edit-username-err',
            FORM = "#hpsum-sug-edit-form",
			PASSWORD_ERR ='#hpsum-sug-edit-password-err',
            CREDENTIALS_PANEL = '#hpsum-sug-edit-credentials',
            BASELINE_PANEL = '#hpsum-sug-edit-baseline';
			var editOptions =  {
                    	hapi: {
                    	username : $(USERNAME).val(),
                    	password : $(PASSWORD).val()
						}
                    };
			
        var ROUTE_PREFIX = '/ilofederation/edit';
                      
        /**
         * Constructor
         */
        function iloFederationEditView() {
          
            var nodeItem=null;
            var formStateView = new FormStateView();
            var baselines='',
                hotfixes='',
                knownilos=[],
                assocBaseline=null,
                newBaseline = null,
                newHotFix  = null,
                assocHotFix = null;
			var baselineChange = false;
            var searchResults = [];
			var addpkgChange = false;
            
            var optiondetails = { 
					hapi: {
					}
           	};
                
            function onItemChange(item) 
            {
            	item = item.hapi;
            	$(USERNAME).val("");
            	$(PASSWORD).val("");
            	
            	if (item) {
                    formStateView.reset();
            		
            		$(GROUPNAME).text(item.sug_name);
                    $(GROUPDESCR).val(item.sug_description);
                    
                    nodeItem= item;
                    newBaseline = null;
    				newHotFix  = null;
    		    if(item.hasOwnProperty("sug_interface_ilo_ip") && item.sug_interface_ilo_ip){
    			$(INTERFACEILO).text(item.sug_interface_ilo_ip);
                        $(CREDENTIALS_PANEL).show();
                        $(BASELINE_PANEL).show();
                    }else {
    			$(INTERFACEILO).html('<a href="#/ilofederation/inventory">' + localizer.getString('hpsum.common.doInventory') + " " + '</a>'+localizer.getString('hpsum.ilofederation.toassignInterfaceIlo'));
                        $(CREDENTIALS_PANEL).hide();
                        $(BASELINE_PANEL).hide();

                    }
    					
                    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 = baseline; 
                    				$(CURRENT_HOTFIX).text(baseline.name);
									$(HOTFIX).hpSearchCombo('set', {id: baseline.id, name: baseline.name});
                    			}else{
                    				$(CURRENT_BASELINE).text(baseline.name);
									$(BASELINES).hpSearchCombo('set', {id: baseline.id, name: baseline.name});
                    				assocBaseline = baseline;
                    			}
                    		}
                    	}
 					 }
 					 else {
 					 	$(CURRENT_BASELINE).text('');
						editOptions.hapi.baselines = {remove_existing_baselines:'true'};
                         $(CURRENT_HOTFIX).text('');
 					 }
 				} else {
                    $(GROUPNAME).text("");
                    $(GROUPDESCR).val("");
                }
                
            }
            
            function onEdit() 
            {
               var baselinesdata = [];
               if($(BASELINES).val())
                   baselinesdata.push($(BASELINES).val());

               if($(HOTFIX).val())
                  baselinesdata.push($(HOTFIX).val());
               if(baselinesdata.length > 0) {
               		optiondetails.hapi.baselines = {remove_existing_baselines:'false'};
               		optiondetails.hapi.baselines.baseline = baselinesdata;
               }
               else
               {
               		optiondetails.hapi.baselines = {remove_existing_baselines:'true'};
               		optiondetails.hapi.baselines.baseline = baselinesdata;
               }
               
               optiondetails.hapi.sug_description = $(GROUPDESCR).val();
               optiondetails.hapi.username = $(USERNAME).val();
               optiondetails.hapi.password = $(PASSWORD).val();
               
               presenter.setattribute(nodeItem,optiondetails, {
						success : function(data) {
							$(CANCEL).trigger('click');
						},
						error : onsetattributeerror
				});
            }
            
            function onsetattributeerror(error) {
            	notifications.show(error);
            	$(FAILEDPANEL).show();
                if(errorMessage){
                    $(FAILEDMSG).text(errorMessage);
                    formStateView.setMessage({
                            summary : errorMessage,
                            status : "error"
                        });
                    }
                else{
                    $(FAILEDMSG).text(localizer.getString('hpsum.ilofederation.editError'));
                    formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.editError'),
                            status : "error"
                        });
                    }
                    
                $(OK).attr("disabled", "disabled");
            }            
            
			function OnResize(){
				var BaseLineSearchWidth = ($(window).width() / 3);
				$(BASELINES).hpSearchCombo({getResults:getBaseline, width:BaseLineSearchWidth});
				$(HOTFIX).hpSearchCombo({getResults: getHotfixes, width:BaseLineSearchWidth});
			}
			
			
            function changeLocation(location) {
                
            }
            
            this.resume = function () {
                presenter.on('itemChange', onItemChange);
                $(PANELS).hpStackedPanels('resume');
                 baselines = hotfixes = localizer.getString('hpsum.common.loading');
                    presenter.getAllBaselines({
                            success:getBaselinesSuccess,
                            error: getBaselinesError
                    });
                $(OK).removeAttr("disabled");
                $(USERNAME).removeClass("hp-error");
            	$(PASSWORD).removeClass("hp-error");
                $(USERNAME_ERR).hide();
				$(PASSWORD_ERR).hide();    
            };
            
            this.pause = function () {
                presenter.off('itemChange', onItemChange);
                $(GROUPNAME).val('');
                $(BASELINES).hpSearchCombo('set', {id:'', name: ''});
                $(HOTFIX).hpSearchCombo('set', {id:'', name: ''});
                $(PANELS).hpStackedPanels('pause');
                $(USERNAME_ERR).hide();
				$(PASSWORD_ERR).hide();
				$(CURRENT_BASELINE).text('');
                $(CURRENT_HOTFIX).text('');
                formStateView.reset();
            };
            
            /**
             * @public
             */
            this.init = function () {
              
                $(FAILEDPANEL).hide();
                $(CANCEL).click(function () {
                    formStateView.reset();
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                });
                $(PANELS).hpStackedPanels({
                        panelSelector : PANEL_SELECTOR
                    });

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

                //Baselines
	
				$(window).on('resize', OnResize);
                //set width for baseline and additional package search box.
				OnResize();
                $(OK).on('click', function(ev) {
                    onEdit();
                    ev.preventDefault();
                });
                $(OK).removeAttr("disabled");

                router.watch('ilofederation edit section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
				
				$(BASELINES).change(function (ev, value) {
                    var item = presenter.getBaselineDetailsforId(value);
                    if(item){
                        newBaseline = item;
                        $(CURRENT_BASELINE).text(newBaseline.name);
                    } else {
                    	newBaseline='';                        
                        $(CURRENT_BASELINE).text('');                        
                    }
					
					baselineChange = true;
					if(baselineChange)
						$(OK).attr('disabled', false);
                });

                $(HOTFIX).change(function (ev, value) {
                    var item = presenter.getBaselineDetailsforId(value);
                    if(item){
                        newHotFix = item;
                        $(CURRENT_HOTFIX).text(newHotFix.name);
                    } else {
                    	newHotFix='';
                        $(CURRENT_HOTFIX).text('');  
                    }
					addpkgChange = true;
					if(addpkgChange)
						$(OK).attr('disabled', false);
                });

                this.resume();
            };

            function getBaseline(string, handlers,count,start){
                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,count,start){
                    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 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)
            {
                
            }


        }

        return new iloFederationEditView();
    }());
    
    return iloFederationEditView;
});
