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

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

    var IloOverviewView = (function() {
      
        var ROOT = '#hpsum-ilo-show-overview';
        var PANELS = '.hp-grid-panels',
        	DESCRIPTION = '#hpsum-ilo-description',
        	TYPE = '#hpsum-ilo-type',
        	BASELINE = '#hpsum-ilo-bundle',
			ADDPACKAGE = '#hpsum-ilo-additional-bundle',
        	LOCATION = '#hpsum-ilo-location',
        	OA = '#hpsum-ilo-oa',
			ASSOC_DEVICES = '#hpsum-iLO-assocdevices',
			NO_ASSOC_DEVICES = '#hpsum-iLO-no-devices',
        	INSTALLEDROM = '#hpsum-ilo-installed-rom',
        	ACTIVEROM = '#hpsum-ilo-active-rom',
        	MATRIXENABLED = '#hpsum-ilo-matrix-enabled',
        	MATRIXVERSION = '#hpsum-ilo-matrix-version',
			GROUP = '#hpsum-server-group',
        	SPINNER = '#hpsum-node-add-spinner',
            INSTALL_LOGS = '#hpsum-ilo-install-log',
			EDIT_GENERAL = '#hpsum-ilo-general-edit',
			WARNING_MSG = '#hpsum-warning-messages',
            ILOINSTALLSET_PANEL = '#hp-installset-panel',
			OVERVIEW_CONTENTS_TABS = '#hp-overview-contents-tabs-panel',
            ASSOCIATED_OA = '#hpsum-ilo-assOA',
            ASSOCIATED_SERVER = '#hpsum-ilo-server',
			OS_INSTALLED = '#hpsum-ilo-installedOS',
            SYSROM ='#hpsum-ilo-server-sysrom',
        	SERVER_TYPE = '#hpsum-ilo-server-type',
        	CPU = '#hpsum-ilo-server-cpu',
        	MEMORY ='#hpsum-ilo-server-memory';
      
        /**
         * Constructor
         */
        function IloOverviewView() {
          
            var noItem;
            var timer= null;
            var thisNode=null;
            
            function onItemChange(item) {
            	item = item.hapi;
            	thisNode =item;
                noItem.remove();
				$(ASSOC_DEVICES).html('');
				$(NO_ASSOC_DEVICES).show();				
				$('#hpsum-iloinstallsets').hpsumInstallSets('destroy');
				$('#hpsum-overviewContents').overviewContentsAsTabs('destroy');
        		item.type = item.type.toLowerCase();
        		var uitype = presenter.getUINodeType(item.type);
        		$(ROOT).closest('section').show();
        		
        		if(!router.location().match(uitype)) {
        		    if(router.location().indexOf("/node") == 0)
        		    	router.go((urlFragment.replaceView(router.location(), 'show/' + item.type + '/overview')), "ilo show overview");
        		    else {
        		    	$(ROOT).closest('section').hide();
        		      	return;
        		    }
                }
        		
        		
				$(EDIT_GENERAL).attr('href', presenter.getGeneralEditHref(router.location(), uitype));
				
				$(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();
        		//	 getNodeStatus(item);
        		}
        		else {
        			$(SPINNER).hide();
        			//$(NO_ASSOC_DEVICES).hide();
					//$(ASSOC_DEVICES).hide();
					$('.hp-grid-panels').css({"display":""});
        			$('.hp-grid-panels').hpGridPanels('reset');     			
        			$(DESCRIPTION).text(item.description);
        			if(item.hasOwnProperty('serial_number'))
        				$(LOCATION).text(item.serial_number);
        			else 
        				$(LOCATION).text('');
        			if(item.hasOwnProperty('version')){
						//$(NO_ASSOC_DEVICES).hide();
						//$(ASSOC_DEVICES).show();
        				$(INSTALLEDROM).text(item.version);
        				$(ACTIVEROM).text(item.active_version);
						var node_uri = "/Session/" + session.getToken() + "/node/" + item.node_id;
						rest.getURI(node_uri +"/getAssociatedNodesCompData",
						{
							nodeid : item.node_id,
							success : function(data) {
							var nodeAssoData = data.hapi.associated_nodes;
							showAssociatedDevices(item,nodeAssoData);
							$(PANELS).hpGridPanels();
							},
							error : function(errorInfo){ }
						});				
        			}
        			else{
        				$(INSTALLEDROM).text('');
        				$(ACTIVEROM).text('');
        				//$(NO_ASSOC_DEVICES).show();
						//$(ASSOC_DEVICES).hide();
        			}
        			
        			if(item.product_id == undefined)
        				$(TYPE).text(displayILO(item.type));
        			else {
        				$(TYPE).text(displayILO(item.product_id));
					}
        		    
        		    //default values..

        			$(MEMORY).text("");
        			$(SERVER_TYPE).text("");
        			$(SYSROM).text("");
        			$(CPU).text("");
        		    //populate iLO5 specific details.. 
        			if (item.type.match(/ilo5/i)) {
        			    var mem = "";
        			    if (item.hasOwnProperty('rom_version')) {
        			        $(SYSROM).text(item.rom_version);
        			        if (item.hasOwnProperty('vendor') && item.hasOwnProperty('architecture')) {
        			            $(CPU).text(item.vendor + ' ' + item.architecture);
        			        }
        			        if (item.hasOwnProperty('memory')) {
        			            mem = item.memory + " GB"; //from iLO we get value in GB only. so no need to of converting it further to MB or KB
        			        }
        			        $(MEMORY).text(mem);
        			        $(SERVER_TYPE).text(item.server_type);
        			    }
        			}
        			$(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');
        			}

        			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.type.match(/ilo5/i) && 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'));  

                    $("#hpsum-ilo-viewlogs a").addClass("company-a").text("View Log");
                    $('a.hp-button', $(INSTALL_LOGS)).attr('href', '#/' + urlFragment.getPage(router.location()) + '/deploy-results');
                    if ((item.type.match(/ilo5/i) && item.node_state.match(/idle/i)))
                    {
                        $(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-ilo-viewlogs a").addClass("company-a").text("Live Log");
                        $('a.hp-button', $(INSTALL_LOGS)).attr('disabled', false);
                    }else{
                        $(INSTALL_LOGS).hide();
                    }
					if(item.os_installed == "")
					{
						$(OS_INSTALLED).text("none");
					}
					else
					{
						$(OS_INSTALLED).text(item.os_installed);
					}

        		}
                $(PANELS).hpGridPanels('reset');
                $(ROOT).removeClass('hp-show-changing');
                $('.hp-dynamic', ROOT).removeClass('hp-unavailable');
                $(WARNING_MSG).hpsumWarnings(item, false);

                if (item.type.match(/ilo5/i)) {
                    $(ILOINSTALLSET_PANEL).show();
                    $(OVERVIEW_CONTENTS_TABS).show();
                    showiLOInstallSetInfo(item);
                    if (item.node_state.match(/UAN/i)) {
                        showOverviewContents(item, true);
                    }
                    else {
                        showOverviewContents(item, false);
                    }
                }
                else {
                    $(ILOINSTALLSET_PANEL).hide();
                    $(OVERVIEW_CONTENTS_TABS).hide();
                }
            }
           
            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:''; overflow: hidden;");
            }
               
            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
                    };
                    $('#hpsum-overviewContents').overviewContentsAsTabs(contentsOptions);
                }
            }
            
function showAssociatedDevices(item,nodeAssoData)
            {
    if (nodeAssoData && nodeAssoData.hasOwnProperty('node')) {
        if (nodeAssoData.node.length == undefined && nodeAssoData.node.node_id)
            nodeAssoData.node = new Array(nodeAssoData.node);
        if (nodeAssoData.node.length == undefined && nodeAssoData.node.node_id == undefined)
            return;
        if (nodeAssoData.node.length == 0)
            return;
        $(ASSOCIATED_OA).html("");
        $(ASSOCIATED_SERVER).html("");
        for (var i = 0; i < nodeAssoData.node.length; i++) {
            var separator, nodeType;
            if (nodeAssoData.node[i].ipv4 && nodeAssoData.node[i].ipv6)
                separator = " / ";
            else
                separator = "";

            var contents = '';
            var nodeIp = nodeAssoData.node[i].ipv4 + separator + nodeAssoData.node[i].ipv6;
            if (nodeAssoData.node[i].node_id) {
                var assoc_node_url = '#/node/show/r/session/' + session.getToken() + '/node/' + nodeAssoData.node[i].node_id + '/getData';
                contents += '<a href= "' + assoc_node_url + '" class="company-a">' + nodeIp + '</a>';
            }
            else {
                contents += nodeIp;                
            }
            if (nodeAssoData.node[i].type == "SERVER") {
                nodeType = "Server";
                $(ASSOCIATED_SERVER).html(contents);
            }
            else {
                nodeType = nodeAssoData.node[i].type;                
            }
            if (nodeAssoData.node[i].type == "OA") {
                $(ASSOCIATED_OA).html(contents);
            }
        }
    }
}
			
            function getNodeStatus(item){
            	  var ilotimer = setInterval(function () {
            		
            		presenter.getNodeStatus(item, {
                				success : function(data) {
                    				onIloStatusSuccess(data,ilotimer);
                    		 	},
                    			error : function(errorInfo) {
                        			onNodeStatusError(errorInfo,ilotimer);
                    			}
                			});
                			
                }, 3000);
            }
            
            function onIloStatusSuccess(data,ilotimer){
            	if(thisNode.node_id == data.hapi.node_status.node_id) {
            		if(!data.hapi.node_status.node_phase.match(/initialize/i)){
        				clearInterval(ilotimer);
        				ilotimer = 0;
        				presenter.refreshIndexResults();
        			}
        		}
            }   
            function onNodeStatusError(){
            	
            }      
            
            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") {
								$("#ilo-assOA-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);
                $(ASSOCIATED_SERVER).html("");
                $(ASSOCIATED_OA).html("");
            };
            
            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 IloOverviewView();
    }());
    
    return IloOverviewView;
});
