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

    var iloFederationAddView = (function() {

        var FAILEDMSG ='#hpsum-node-inventory-failed-details',
            FAILEDPANEL ='#hpsum-node-inventory-failed',
            OK = '#hpsum-ilofederation-add-ok',
            CANCEL ='#hpsum-ilofederation-close',
            PANEL_SELECTOR = '#hpsum-node-inventory-panel-selector',
            PANELS = '#hpsum-node-inventory-panels',
            BASELINES = '#hpsum-node-add-baselines-search',
            HOTFIX=  '#hpsum-node-add-hotfix-search',
            GROUPNAME = '#hpsum-ilofederation-group-name',
            GROUPDESCR = '#hpsum-ilofed-add-group-descr',
            FORM = '#hpsum-federation-group-form';


        var ROUTE_PREFIX = '/node/inventory';
                      
        /**
         * Constructor
         */
        function iloFederationAddView() {
          
            var inventoryInProgress = false;
            var nodeItem=null;
            var baselines='',
                hotfixes='',
                knownilos=[],
                assocBaseline=null,
                newBaseline = null,
                newHotFix  = null,
                assocHotFix = null;
            var searchResults = [];
                
            
            
            function onItemChange(item) 
            {
               

                
            }
            
            function onAddError(errorMessage) {
                $(FAILEDPANEL).show();
                if(errorMessage)
{
                    $(FAILEDMSG).text(errorMessage);
                    $(OK).attr("disabled", false);
}
                else
                    $(FAILEDMSG).text(localizer.getString('hpsum.ilofederation.inventoryError'));
                    
                $(OK).attr("disabled", "disabled");
                inventoryInProgress = false;
            }

            function onAddSuccess(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 onAdd() 
            {
				$(OK).attr("disabled", true);
               var baselinesdata = [];
               if($(BASELINES).val())
                   baselinesdata.push($(BASELINES).val());

               if($(HOTFIX).val())
                  baselinesdata.push($(HOTFIX).val());

              

              presenter.addGroup( {
                                      group_name : $(GROUPNAME).val(),
                                      group_description : $(GROUPDESCR).val(),
                                      name: $(GROUPNAME).val(),
                                      uri: null
                                  },{
                                        success: function(data){
                                              onAddSuccess(data);
                                          } ,
                                        error:function(data){
                                               onAddError(data);
                                           }
                                  }
                            ); 

            }
            
            
            function changeLocation(location) {
                
            }
            
            this.resume = function () {
                presenter.on('itemChange', onItemChange);
				$(OK).attr('disabled', false);
                $(PANELS).hpStackedPanels('resume');
                 baselines = hotfixes = localizer.getString('hpsum.common.loading');
                    presenter.getAllBaselines({
                            success:getBaselinesSuccess,
                            error: getBaselinesError
                    });
                $(OK).removeAttr("disabled");
                
                
            };
            
            this.pause = function () {
                presenter.off('itemChange', onItemChange);
                $(GROUPNAME).val('');
                $(BASELINES).hpSearchCombo('set', {id:'', name: ''});
                $(HOTFIX).hpSearchCombo('set', {id:'', name: ''});
                $(PANELS).hpStackedPanels('pause');
                $(GROUPDESCR).val('');
            };
            
            /**
             * @public
             */
            this.init = function () {
              
                $(FAILEDPANEL).hide();
                $(CANCEL).click(function () {
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                });
                $(PANELS).hpStackedPanels({
                        panelSelector : PANEL_SELECTOR
                    });

                //Baselines

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

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

                router.watch('ilofederation inventory section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
                
                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 iloFederationAddView();
    }());
    
    return iloFederationAddView;
});
