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

define([//'hpsum/presenter/node/NodePresenter', 
	'hpsum/presenter/ilofederation/iloFederationPresenter',
    'hp/core/UrlFragment',
    'hp/core/Router',
    'hp/core/LinkTargetBuilder',
    'text!hpPages/core/no_details.html',
    'hp/core/Localizer',
	'hp/model/Session',
    'jquery',
    //These two modules required to show table for contents section in details pane
    'lib/jquery.dataTables',
    'lib/jquery.dateFormat',
	'hpsum/view/node/jquery.hpsumWarnings', 
    'hp/lib/jquery.hpGridPanels'],
function(presenter, urlFragment,router, linkTargetBuilder, noneHtml, localizer, session) { "use strict";

    var IloFederationOverviewView = (function() {
      
        var ROOT = '#hpsum-federation-show-overview';
        var PANELS = '.hp-grid-panels',
        	DESCRIPTION = '#hpsum-ilo-federation-desc',
			TPM_WARNING = '#hpsum-ilo-federation-warning',
        	TYPE ='#hpsum-ilo-type',
        	BASELINE='#hpsum-ilo-federation-bundle',
            ADDPACKAGE='#hpsum-ilo-federation-addpackage',
            LOCATION='#hpsum-ilo-location',
            SPINNER = '#hpsum-node-add-spinner',
        SERVER_SECTION='#server_type_section',
            INSTALL_LOGS = '#hpsum-federation-install-log',
            INSTALLED_FW_LIST_TABLE = '#ilofed-installed-fw-contents-table',
            INSTALLED_SYSTEM_TYPE_TABLE = '#ilofed-installed-system-type-table',
            A_INSTALLED_ILO = '#hpsum-installed-ilo',
            A_INSTALLED_BIOS = '#hpsum-installed-bios',
            FW_SELECTTION_TYPE = '#ilo-federation-selection-type',
            INSTALLED_TYPE_TABLE_HEADER = '#hpsum-installed-type-name',
            ILO_FED_GROUP = '#hpsum-ilo-federation-group',
            VERSION_SELECT = '#hpsum-ilofederation-version',
            INTERFACE_IP = '#hpsum-ilo-federation-interfaceip',
            ADDED_BY_USER = '#hpsum-ilo-federation-added-by-user',
            LAST_DISCOVERED = '#hpsum-ilo-federation-last-discovered',
            EDIT_GENERAL = '#hpsum-ilofederation-general-edit',
            NUM_NODES = "#hpsum-ilo-federation-num-nodes",
            POWERED_SERVERS = '#hpsum-ilo-federation-powered-nodes',
            NOT_DISCOVERED = '#hpsum-ilo-federation-not-discovered',
            INVENTORY_FFIRMWARE_VERSION = '#ilofed-inventory-firmware-version',
            ILO_FED_INVENTORY_MSG = '#ilofed-inventory-firmware-msg';

            
        /**
         * Constructor
         */
        function IloFederationOverviewView() {
          
            var noItem;
            var timer= null;
            var thisSUG=null;
            var firmwareItems = null;
            var ilotimer=-1;
            var biosItems = null;
            var iloItems = null;
            var ppicItems = null;
            var cpldItems = null;
                        
            function onItemChange(item) {
            	item = item.hapi;
                
                if(item == null)
                    return;
                    
                thisSUG =item;
                noItem.remove();
				biosItems = null;
				iloItems = null;
                cpldItems = null;
                ppicItems = null;
               
                $("#ilofed-installed-fw-contents-table > tbody > tr").remove();
            	$("#ilofed-installed-fw-contents-table_filter").remove();
            	$("#ilofed-installed-fw-contents-table_processing").remove();
            	$("#ilofed-installed-system-type-table > tbody > tr").remove();
		        $("#ilofed-installed-system-type-table_filter").remove();
            	$("#ilofed-installed-system-type-table_processing").remove();
				if (!item.server_types )
                {
					$(SERVER_SECTION).show();
					$('#ilofed-installed-system-type-table').hide();
                }
                else
				{
                   $(SERVER_SECTION).hide();
				   $('#ilofed-installed-system-type-table').show();
				}
            	

                if(item.sug_state.match(/installdone|idle/i))
                {
                    $(INVENTORY_FFIRMWARE_VERSION).hide();
                    $(ILO_FED_INVENTORY_MSG).show();
                }
                else
                {
                    $(ILO_FED_INVENTORY_MSG).hide();
                    $(INVENTORY_FFIRMWARE_VERSION).show();
                }


				$('a.hp-button' , $(INSTALL_LOGS)).attr('href', '#/' + urlFragment.getPage(router.location()) + '/deploy-results');
                if(item.sug_state.match(/Install$/i)){
                   $(INSTALL_LOGS).show();
                   $("#hpsum-federation-viewlogs a").addClass("company-a").text("Live Log");
                }else{
				   $(INSTALL_LOGS).hide();
				}
				
				$(EDIT_GENERAL).removeClass('hp-disabled').addClass('company-a').unbind('click.disable-link');
				if(item.sug_state.match(/inventory/i) || item.sug_state.match(/installhold/i) || item.sug_state.match(/pendingfwupdate/i) ||
                   item.sug_state.match(/activatependingfwupdate/i) || item.sug_state.match(/scheduled/i) || item.sug_state.match(/Install$/i) || 
				   item.sug_state.match(/Adding_interface_ilo/i) || item.sug_state.match(/activate_pending/i)){
					$(EDIT_GENERAL).removeClass('company-a').addClass('hp-disabled');
					$('.hp-disabled').css("color", "grey");
					$(SERVER_SECTION).hide();

				}
				else if(item.sug_state.match(/idle/i))
				{
					$(SERVER_SECTION).show();
				}
				if(item.warnings)
				{
					$(TPM_WARNING).text(item.warnings[0]);
					$(TPM_WARNING).hpsumWarnings(item, false);
				}
				else
				{
					$(TPM_WARNING).text("");
				}
                $(DESCRIPTION).text(item.sug_description);
        		$(INTERFACE_IP).text(item.sug_interface_ilo_ip);
                $(NUM_NODES).text(localizer.getString('hpsum.common.na'));
                $(POWERED_SERVERS).text(localizer.getString('hpsum.common.na'));

                //We are indicating if the group was auto discovered or not. This is will be not of sug_added_by_user
                if(item.sug_added_by_user.match(/no/i))
                {
                    $(ADDED_BY_USER).text(localizer.getString('hpsum.common.button.yes'));
                }
                else
                {
                    $(ADDED_BY_USER).text(localizer.getString('hpsum.common.button.no'));
                }

                if(item.sug_stale_group){
                    $(LAST_DISCOVERED).html(item.sug_last_discovered+'<div id="hpsum-ilo-federation-not-discovered" class="hpsum-round-bang"  style="margin-left:10px; display:inline-block"></div>');
                    $(NOT_DISCOVERED, $(LAST_DISCOVERED)).attr("tooltip", localizer.getString('hpsum.ilofederation.notDiscoveredinthisSession') ).hpTooltip();
                }else{
                    $(LAST_DISCOVERED).html(item.sug_last_discovered);
                }
                $(BASELINE).text(localizer.getString('hpsum.node.noBaselineDefined'));
                $(ADDPACKAGE).text(localizer.getString('hpsum.node.noBaselineDefined'));

        		if( item.sug_state.match(/InActive/i))   			
                {
                    $('.hp-grid-panels').css({"display":"none"});
                    $(SPINNER).show();
                    getGroupStatus(thisSUG);
                }
                else if( item.sug_state.match(/Not_on_network/i))
                {
                    $('.hp-grid-panels').css({"display":"none"});
                    $(SPINNER).hide();
                }
                else if( item.sug_state.match(/install/i))
                {
                    $(NUM_NODES).text(item.node_count);
                    $(POWERED_SERVERS).text(item.powered_on_servers);
                }
        		else if(item.sug_state.match(/idle/i)){
        			
        			 $(SPINNER).hide();
        			 $('.hp-grid-panels').css({"display":""});
        			 $('.hp-grid-panels').hpGridPanels('reset');  
                }
        		else 
                {
        			$(SPINNER).hide();
					$('.hp-grid-panels').css({"display":""});
        			$('.hp-grid-panels').hpGridPanels('reset');     			 
					
					
                    if (item.sug_state.match(/uan/i)) {

						
                        // Populate the all the discovered server models and counts
                        if (item.server_types && item.server_types.length > 0) {
							
							var systemsTable = initSystemsTable();
							systemsTable.fnClearTable();
							// Go ahead and populate all the systems in the systems table
                            var idx;
                            for (idx = 0; idx < item.server_types.length; idx++) {
                                var system = item.server_types[idx];
                                systemsTable.fnAddData([{server_model : system.server_model, count : system.count}]);
                            }
                        }

                        if (item.bios && item.bios.devices)
                            biosItems = item.bios.devices;
                        if (item.ilo && item.ilo.devices)
                            iloItems = item.ilo.devices;
                        if (item.cpld && item.cpld.devices)
                            cpldItems = item.cpld.devices;
                        if (item.powerpic && item.powerpic.devices)
                            ppicItems = item.powerpic.devices;

                        if (iloItems) {
                            // Simulate selection of the iLO to populate the iLO details for the first time
                            $(VERSION_SELECT).selectBox('value', "iLo");
                            populateFirmwareListTable();
                        }
                        $(NUM_NODES).text(item.node_count);
                        $(POWERED_SERVERS).text(item.powered_on_servers);
                        
                    }

                }

                if(item.sug_state.match(/installdone/i))
                {
                    //We dont have any logs to display in iLO federation offline mode and we show logs only for online mode
                    //Enable it when installation logs are available
                    if(item.deploy_mode == 0) {
                        $(INSTALL_LOGS).show();
                        $("#hpsum-federation-viewlogs a").addClass("company-a").text("View Log");
                    }                    
                }
                

                if( !item.sug_state.match(/InActive/i))  
                {

                     var Baseline = presenter.getFWBaseline(item.sug_baselines);
                    if(Baseline.fwbaseline){
                            var baseline_url = '#/baseline/show/r'+Baseline.fwbaseline.uri +'/getBaselineData';
                            name = Baseline.fwbaseline.name;
                            $(BASELINE).html('<a href="'+ baseline_url +'" class="company-a">'+name+ '</a>');
                    }
                    else
                        $(BASELINE).text(localizer.getString('hpsum.node.noBaselineDefined')); 
                    //Do the same for Additional Packages too
                    if(Baseline.addpackage){
                            var baseline_url = '#/baseline/show/r'+Baseline.addpackage.uri +'/getBaselineData';
                            name = Baseline.addpackage.name;
                            $(ADDPACKAGE).html('<a href="'+ baseline_url +'" class="company-a">'+name+ '</a>');
                    }
                    else
                        $(ADDPACKAGE).text(localizer.getString('hpsum.group.noAdtPackage')); 
               }

                $(PANELS).hpGridPanels('reset');
                $(ROOT).removeClass('hp-show-changing');
                $('.hp-dynamic', ROOT).removeClass('hp-unavailable');
            }
            
            
            function getGroupStatus(item)
            {

                 if(ilotimer == -1)
                 {

                    ilotimer = setInterval(function () {

                        presenter.getSUGStatus(item, {
                                success : function(data) {
                                            onIloFederationStatusSuccess(data,ilotimer);
                                         },
                                error : function(errorInfo) {
                                            onIloFederationStatusError(errorInfo,ilotimer);
                                        }
                        });
                        }, 3000);
                }
            }
            
            function onIloFederationStatusSuccess(data,ilotimer){
            	if(thisSUG.sug_id == data.hapi.sug_id) {
            		if(!data.hapi.sug_state.match(/inactive/i)){
        				clearInterval(ilotimer);
        				ilotimer = -1;
        				presenter.refreshIndexResults();
        			}
        		}
            }   
            function onIloFederationStatusError(){
                clearInterval(ilotimer);
            	ilotimer =-1
                //We need to show the login page.Since we failed to communicate to the 
                //hpsum_service
            }      
            
            function onItemError(error) {
                $(ROOT).append(noItem);
            }
            
            function onSelectionChange(selection) {
                //clearNotifications();
                urlFragment.replaceHrefUris(ROOT, selection.uris);
                if ($(ROOT).hasClass('hp-show-init')) {
                    $(ROOT).removeClass('hp-show-init');
                } else {
                    $(ROOT).addClass('hp-show-changing');
                    //$(ACTIONS).addClass('hp-disabled');
                }
            }
          
            /**
             * @public
             */
            this.resume = function() {
            	$(PANELS).hpGridPanels('reset');
                presenter.on("selectionChange", onSelectionChange);
                presenter.on("itemError", onItemError);
                presenter.on("itemChange", onItemChange);
                $(VERSION_SELECT).on('change',populateFirmwareListTable);
                $(VERSION_SELECT).selectBox('value', "iLo");

            };
            
            this.pause = function() {
            	presenter.off("selectionChange", onSelectionChange);
                presenter.off("itemChange", onItemChange);
                presenter.off("itemError", onItemError);
                $(VERSION_SELECT).off('change');
            };


            function populateFirmwareListTable(event) {

                var type = $(VERSION_SELECT).val();

                var idx;
                var devices = null;

                if (type == "iLo" && iloItems) {
                    $(INSTALLED_TYPE_TABLE_HEADER).text(localizer.getString('hpsum.ilofederation.ilotype'));
                    devices = iloItems;
                    $(FW_SELECTTION_TYPE).text(localizer.getString('hpsum.common.ilo'));
                } else if (type == "Bios" && biosItems) {
                    $(INSTALLED_TYPE_TABLE_HEADER).text(localizer.getString('hpsum.baseline.custom.systemrom'));
                    devices = biosItems;
                    $(FW_SELECTTION_TYPE).text(localizer.getString('hpsum.common.bios'));
                } else if(type == "Powerpic" && ppicItems)
                {
                    $(INSTALLED_TYPE_TABLE_HEADER).text(localizer.getString('hpsum.ilofederation.powerpictype'));
                    devices = ppicItems;
                    $(FW_SELECTTION_TYPE).text(localizer.getString('hpsum.common.powerpic'));
                } else if (type == "CPLD" && cpldItems)
                {
                    $(INSTALLED_TYPE_TABLE_HEADER).text(localizer.getString('hpsum.ilofederation.cpldtype'));
                    devices = cpldItems;
                    $(FW_SELECTTION_TYPE).text(localizer.getString('hpsum.common.cpld'));
                }

				var fwListTable = initFWListTable();
				fwListTable.fnClearTable();
				
                if( devices )
                {
                    for (idx = 0; idx < devices.length; idx++) {
                        var obj = devices[idx];
                        fwListTable.fnAddData([{product: obj.product, version: obj.version, count: obj.count}]);
                    }
                }

            }
             
			function initFWListTable() {
				
				if($.fn.DataTable.fnIsDataTable( $(INSTALLED_FW_LIST_TABLE)[0] ))
				{
					$(INSTALLED_FW_LIST_TABLE).dataTable().fnDestroy();	
				}
				
				return $(INSTALLED_FW_LIST_TABLE).dataTable({
				oLanguage: {
						sSearch: localizer.getString('hpsum.common.search')
					},
                    bPaginate : false,
                    bLengthChange : false,
                    bFilter : true,
                    bSort : true,
                    bInfo : false,
                    bAutoWidth : false,
                    bRetrieve : true,
				    bDestroy : true,
				    aoColumns : [				        
                        {mDataProp: 'product'},
                        {mDataProp: 'version'},
                        {mDataProp: 'count'}
                        ],
                    aaSorting: [[ 0, "desc" ]]
                });
			}
			
			function initSystemsTable() {
				
				if($.fn.DataTable.fnIsDataTable( $(INSTALLED_SYSTEM_TYPE_TABLE)[0] ))
				{
					$(INSTALLED_SYSTEM_TYPE_TABLE).dataTable().fnDestroy();	
				}  
								
				return $(INSTALLED_SYSTEM_TYPE_TABLE).dataTable({
				oLanguage: {
						sSearch: localizer.getString('hpsum.common.search')
					},
                    bPaginate : false,
                    bLengthChange : false,
                    bFilter : true,
                    bSort : false,
                    bInfo : false,
                    bAutoWidth : false,
                    bRetrieve : true,
				    bDestroy : true,
				    aoColumns : [				        
                        {mDataProp: 'server_model'},
                        {mDataProp: 'count'}
                        ]
                });
			}

            this.init = function() {
            	if(!presenter.initDone)
            		presenter.init();
                noItem = $(noneHtml);
                $(PANELS).hpGridPanels();
				$(SERVER_SECTION).html('<a href="#/ilofederation/inventory">' + localizer.getString('hpsum.common.doInventory') + " " + '</a>'+localizer.getString('hpsum.ilofederation.gatherServerInfo'));
				$(ILO_FED_INVENTORY_MSG).html('<a href="#/ilofederation/inventory">' + localizer.getString('hpsum.common.doInventory') + " " + '</a>'+localizer.getString('hpsum.ilofederation.gatherFwInfo'));
				$(VERSION_SELECT).selectBox({autoWidth: false});
                $(VERSION_SELECT).on('change',populateFirmwareListTable);

                this.resume();
            };
        }

        return new IloFederationOverviewView();
    }());
    
    return IloFederationOverviewView;
});
