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

define(['hpsum/presenter/node/NodePresenter', 
    'hp/core/UrlFragment',
	'hp/model/Session',
    'hp/core/Router',
    'hp/core/LinkTargetBuilder',
    'text!hpPages/core/no_details.html',
    'hp/core/Localizer',
    'jquery',
    'lib/jquery.dataTables',
    'hpsum/view/node/jquery.hpsumWarnings', 
    'hp/lib/jquery.hpGridPanels'],
function(presenter, urlFragment, session, router, linkTargetBuilder, noneHtml, localizer) { "use strict";

    var ServerShowOverviewView = (function() {
      
        var ROOT = '#tour-server-show-overview';
        var PANELS = '.hp-grid-panels',
        	DESCRIPTION = '#hpsum-server-description',
        	TYPE ='#hpsum-server-type',
        	BASELINE='#hpsum-server-bundle',
			ADDPACKAGE = '#hpsum-server-additional-bundle',
        	LOCATION='#hpsum-server-location',
        	NPAR='#hpsum-server-npar',
        	NPAR_DETAIL = '#hpsum-npar-detail',
        	ILO = '#hpsum-server-ilo',
        	OA = '#hpsum-server-oa',
        	SYSROM ='#hpsum-server-sysrom',
        	OS = '#hpsum-server-os',
        	CPU	= '#hpsum-server-cpu',
        	MEMORY ='#hpsum-server-memory',
            GROUP = '#hpsum-server-group',
            SPINNER = '#hpsum-node-add-spinner',
            INSTALL_LOGS = '#hpsum-server-install-log',
			EDIT_GENERAL = '#hpsum-server-general-edit',
            ILOINSTALLSET_PANEL = '#hp-installset-panel',
			POWER_SUPPLY_UNIT_COLUMN = "#hpsum-server-power-supply-units-column",
			POWER_SUPPLY_UNIT_TLB_TR = "#hpsum-server-power-supply-units > tbody > tr",
            POWER_SUPPLY_UNIT_FILTER = "#hpsum-server-power-supply-units_filter",
            OVERVIEW_CONTENTS_TABS = '#hp-overview-contents-tabs-panel',
            POWER_SUPPLY_UNIT_PROCESSING = "#hpsum-server-power-supply-units_processing",
            ASSOCIATED_ILO = '#hpsum-server-assilo';

        var emptyTableMessage = "";		
        /**
         * Constructor
         */
        function ServerShowOverviewView() {
          
            var noItem,
            	thisNode = null;
            
            function onItemChange(item) {
            	item = item.hapi;
            	thisNode = item; 
                noItem.remove();
                
        		item.type = item.type.toLowerCase();
        		var uitype = presenter.getUINodeType(item.type);
        		$(ROOT).closest('section').show();        		
        		$('#hpsum-iloinstallsets').hpsumInstallSets('destroy');
        		$('#hpsum-overviewContents').overviewContentsAsTabs('destroy');
        		if(!router.location().match(uitype)) {
        		    if(router.location().indexOf("/node") == 0)
        		    	router.go((urlFragment.replaceView(router.location(), 'show/' + item.type + '/overview')), "server show overview");
        		    else {
        		    	$(ROOT).closest('section').hide();
        		      	return;
        		    }
                }
                
                $(EDIT_GENERAL).attr('href', presenter.getGeneralEditHref(router.location(), uitype));
                				
                $(NPAR_DETAIL).hide();

                
               
				
				$(EDIT_GENERAL).removeClass('hp-disabled').addClass('company-a').unbind('click.disable-link');
				if(item.node_state.match(/inventory/i) || item.node_state.match(/installhold/i) || item.node_state.match(/pendingfwupdate/i) ||
                   item.node_state.match(/activatependingfwupdate/i) || item.node_state.match(/scheduled/i) || item.node_state.match(/Install$/i) || 
				   item.node_state.match(/activate_pending/i)){
					$(EDIT_GENERAL).removeClass('company-a').addClass('hp-disabled');
					$('.hp-disabled').css("color", "grey").bind('click.disable-link', function(e) {
						e.preventDefault();
						return false;
					});	
				}
				
                if(item.node_state.match(/idle/i) && item.node_phase.match(/initialize/i))
                {
        			$('.hp-grid-panels').css({"display":"none"});
        			 $(SPINNER).show();
        			 presenter.startNodeStatus(item);
        		}
        		else {
        			$(SPINNER).hide();
        			$('.hp-grid-panels').css({"display":""});
        			$('.hp-grid-panels').hpGridPanels('reset');
        			$(DESCRIPTION).text(item.description);
        			if(item.hasOwnProperty('rom_version')) {
        				$(LOCATION).text(item.serialnumber);
        				$(OS).text(item.os);
        				$(SYSROM).text(item.rom_version);
        				$(CPU).text(item.vendor + ' ' +item.architecture);
						var mem = item.memory;
        				if (mem >= 1024)
						{
						   mem = (mem/1024).toFixed(2);
						   if (mem >=1024)
						   {
						     mem = (mem/1024).toFixed(3);
							 mem = mem + "GB";
						   }
						   else 
						   mem = mem + "MB";
						}
						else 
						mem = mem + "KB";
						$(MEMORY).text(mem);
        				$(TYPE).text(item.server_type);
        			}
        			else {
        				$(LOCATION).text('');
        				$(OS).text(item.type.match(/hpux/i) ? "HP-UX" : item.type);
        				$(SYSROM).text('');
        				$(CPU).text('');
        				$(MEMORY).text('');
                        $(GROUP).text('');
        				$(TYPE).text('');
        			}
        			if(item.hasOwnProperty('npartition_id')) {
        			    $(NPAR_DETAIL).show();
        				$(NPAR).text(item.npartition_id);
					} else {
        				$(NPAR).text('');
					}
					
				    if(item.hasOwnProperty('ilo_address')) {
				        $(ILO).text(item.ilo_address);
				        $(ILO).parent().show();
				    } else {
				        $(ILO).text('');
				        $(ILO).parent().hide();
				    }
				    if(item.hasOwnProperty('oa_address')) {
				        $(OA).text(item.oa_address);
				        $(OA).parent().show();
				    } else {
				        $(OA).text('');
				        $(OA).parent().hide();
				    }
				    $(ASSOCIATED_ILO).text('NA');
				    if (item.server_generation >= 10) {
                        //find associated ILO only for gen10 server. 
				        if (item.hasOwnProperty('node_ilo_address')) {
				            $(ASSOCIATED_ILO).text(item.node_ilo_address);
				        }
                        $(ILOINSTALLSET_PANEL).show();				        
				        showiLOInstallSetInfo(item);
				    }
				    else {
                        $(ILOINSTALLSET_PANEL).hide();
				    }

                    if (item.node_state.match(/UAN/i))
                    {
                        showOverviewContents(item, true);
                    }
                    else {
                        showOverviewContents(item, false);
                    }
				    var fwBaselines =presenter.getFWBaselineAndPackage(item.baselines);
				
				    if (fwBaselines.fwbaseline) {
				        var baseline_url = '#/baseline/show/r' + fwBaselines.fwbaseline.uri + '/getBaselineData';
				        name = fwBaselines.fwbaseline.name;
				        $(BASELINE).html('<a href="' + baseline_url + '" class="company-a">' + name + '</a>');
				    }
				    else 
				    {
			         if (item.server_generation >= 10 && item.baselines.length > 0 && item.baselines[0].indexOf('/') == -1) {
				            if (item.baselines[0].match(/ilo_queued_updates/i)) {
				                $(BASELINE).text(localizer.getString('hpsum.common.pendingTaskQueue'));
				            }
				            else {
				                var installItem = {
				                    node_id: item.node_id,
				                    installset_id: item.baselines[0]
				                };

				                presenter.getInstallSetDetails(installItem, {
				                    success: function (data) {
				                        //check if its an installset. 
				                        if (data.hapi.hasOwnProperty('installset') && item.baselines == data.hapi.installset.id) {

				                            $(BASELINE).text(data.hapi.installset.name);
				                        }
				                        else {
				                            $(BASELINE).text(localizer.getString('hpsum.node.noBaselineDefined'));
				                        }
				                    },
				                    error: function () {

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

                    if(item.operation_mode != 0)
                    {
                        /* means not InventoryMode*/
                        emptyTableMessage = localizer.getString('hpsum.node.nodeInfoNotAvailable');
                    }
                    else
                    {
                        emptyTableMessage = localizer.getString('hpsum.node.noItemsFound');
                    }		
                    $("#hpsum-server-viewlogs a").addClass("company-a").text("View Log");
                    $('a.hp-button', $(INSTALL_LOGS)).attr('href', '#/' + urlFragment.getPage(router.location()) + '/deploy-results');
                    if ((item.server_generation >= 10 && item.node_state.match(/idle/i) && item.logs_available == true)) {
                        $(INSTALL_LOGS).show();
                        if (item.logs_available) {
                            $('a.hp-button', $(INSTALL_LOGS)).attr('disabled', false);                        
                        } else {
                            $('a.hp-button', $(INSTALL_LOGS)).attr('disabled', 'disabled');
                            $('a.hp-button', $(INSTALL_LOGS)).attr('href', 'javascript:void(0);');
                        }
                    }
                    else if ((item.node_state.match(/installdone/i) && item.node_status != 'No component(s) deployed.') || ((item.node_state.match(/error/i) && item.logs_available == true))) {
                        $(INSTALL_LOGS).show();
                        $('a.hp-button', $(INSTALL_LOGS)).attr('disabled', false);
                        
                    }
                    else if ((item.node_state.match(/INSTALLFROMILOTASKQUEUE|INSTALLFROMRECOVERYSET|Install$/i))) {
                        $(INSTALL_LOGS).show(); 
                        $("#hpsum-server-viewlogs a").addClass("company-a").text("Live Log");
                        $('a.hp-button', $(INSTALL_LOGS)).attr('disabled', false);
					}
					else if (item.node_state.match(/UAN/i) && item.logs_available == true){
						$(INSTALL_LOGS).show(); 
						$('a.hp-button', $(INSTALL_LOGS)).attr('disabled', false); 
					}
                    else{
                        $(INSTALL_LOGS).hide();
                    }
                                  
        		}
                $(PANELS).hpGridPanels('reset');
                $(GROUP).text('');
                if (item.hasOwnProperty('group_name')) {
                    if (item.group_name.length == 0) {
                        $(GROUP).text('none');
                    }
                    else {
                        var group_uri = '#/group/show/overview/r/session/' + item.node_session + '/node/group/' + item.group + '/getdata';
                        var uri = '<a href="' + group_uri + '" class="company-a">' + item.group_name + '</a>';
                        $(GROUP).html(uri);
                    }
                }
                else {
                    $(GROUP).text('none');
                }
			
                $(ROOT).removeClass('hp-show-changing');
                $('.hp-dynamic', ROOT).removeClass('hp-unavailable');
                $('#hpsum-warning-messages').hpsumWarnings(item, false);
            }
			
			function showiLOInstallSetInfo(item)
			{
				var options = {
							command:'init',
							nodeItem:item
						};
				//Call plugin to show the component list ();
				$('#hpsum-iloinstallsets').hpsumInstallSets(options);
				$('.hp-panel-contents-container').attr('style', "width:''; height:'';");
			}		

			function showOverviewContents(item, updatedContent) {
			    
			    //Call plugin to show the contents list ();
			    $('#hpsum-overviewContents').overviewContentsAsTabs('init');
			    if (updatedContent)
			    {
			        var options = {
			            command: 'rePopulateOverviewContents',
			            item: item
			        };
			        $('#hpsum-overviewContents').overviewContentsAsTabs(options);			        
			    }
			    else {
			        var contentsOptions = {
			            command: 'init',
			            item: item
			        };
			    //Call plugin to show the contents list ();
			        $('#hpsum-overviewContents').overviewContentsAsTabs(contentsOptions);
			    }

			}
            
            
            function onItemError(error) {
                $(ROOT).append(noItem);
            }
            
            function onSelectionChange(selection) {
                urlFragment.replaceHrefUris(ROOT, selection.uris);
                if ($(ROOT).hasClass('hp-show-init')) {
                    $(ROOT).removeClass('hp-show-init');
                } else {
                    $(ROOT).addClass('hp-show-changing');
                    $('#tour-server-bundle-item').addClass('hp-show-changing');
                }
            }
			
			function updateUserInterfaceForOEM()
			{
				var sessionDataHandlers = {
					success : function(data) {
						// if hcode is 0 then session is alive and set session cookies
						if(data.hapi.hcode == 0) {
							var mfg = data.hapi.manufacturer;
							if (mfg != "HP" && mfg != "HPE") {
								$("#assilo-li").remove();
							}
						}
						else
						{
							// if session is expired or any other error, then goto login page
							session.eraseAll();
							document.location.href = "/#/login";
						}
					},
					error : function(jqXHR) {
						// getsessiondata failed, so goto login page
						session.eraseAll();
						document.location.href = "/#/login";
					}
				};

				//get session data and set user and login details for the session
				session.getSessionData(sessionDataHandlers);
			}
          
            /**
             * @public
             */
            this.resume = function() {
                $(PANELS).hpGridPanels('reset');
                presenter.on("selectionChange", onSelectionChange);
                presenter.on("itemError", onItemError);
                presenter.on("itemChange", onItemChange);
                
            };
            
            this.pause = function() {
                presenter.off("selectionChange", onSelectionChange);
                presenter.off("itemChange", onItemChange);
                presenter.off("itemError", onItemError);
                $('#hpsum-iloinstallsets').hpsumInstallSets('destroy');
            };
             
            this.init = function() {
            	if(!presenter.initialized())
            		presenter.init();			    
                noItem = $(noneHtml);
                $(PANELS).hpGridPanels();
				updateUserInterfaceForOEM();
                this.resume();
            };
        }

        return new ServerShowOverviewView();
    }());
    
    return ServerShowOverviewView;
});
