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

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

    var SwitchOverviewView = (function() {
      
      	var ROOT = '#hpsum-switch-show-overview';
        var VIEW = '.hp-details-show-section',
        	MODEL ='#hpsum-switch-model',
        	DESCRIPTION ='#hpsum-switch-description',
        	WWN = '#hpsum-switch-wwn',
			WWN_FORM_ITEM = '#hpsum-switch-overview-wwn',
        	FWVERSION = '#hpsum-switch-fw',
        	BASELINE='#hpsum-switch-bundle',
			ADDPACKAGE = '#hpsum-switch-additional-bundle',
        	NOASSOC ='#hpsum-switch-noassocdevices',
        	ASSOC ='#hpsum-switch-assocdevices',
        	PARTNER ='#hpsum-switch-partner',
        	PARTNERWFW ='#hpsum-switch-partner-writtenfw',
        	PARTNERAFW ='#hpsum-switch-partner-activefw',
			GROUP = '#hpsum-server-group',
		PARTNERIP ='#hpsum-switch-partnerip',
        	OA ='#hpsum-switch-oa',
        	SPINNER = '#hpsum-node-add-spinner';
        var GRAPHIC_CONTAINER = '.hp-overview-graphic';
        var INSTALL_LOGS = '#hpsum-switch-install-log',
		    EDIT_GENERAL = '#hpsum-switch-general-edit';
        /**
         * Constructor
         */
        function SwitchOverviewView() {
            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();
        		
	        	if(!router.location().match(uitype)) {
        		    if(router.location().indexOf("/node") == 0)
        		    	router.go((urlFragment.replaceView(router.location(), 'show/' + item.type + '/overview')), "switch show overview");
        		    else {
        		    	$(ROOT).closest('section').hide();
        		      	return;
        		    }
                }
                
                $(EDIT_GENERAL).attr('href', presenter.getGeneralEditHref(router.location(), uitype));
                                
                $('a.hp-button' , $(INSTALL_LOGS)).attr('href', '#/' + urlFragment.getPage(router.location()) + '/deploy-results');
                if(item.node_state.match(/Install$/i)){
                   $(INSTALL_LOGS).show();
                   $("#hpsum-switch-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.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();
        			$(NOASSOC).hide();
        			$(ASSOC).hide();
        			$('.hp-grid-panels').css({"display":""});
        			$('.hp-grid-panels').hpGridPanels('reset');     			
        			$(DESCRIPTION).text(item.description);
        			if(item.hasOwnProperty('model_name'))
        				$(MODEL).text(item.model_name);
        			else 
        				$(MODEL).text('');
        			if(item.hasOwnProperty('active_version'))
        				$(FWVERSION).text(item.active_version);
        			else
        				$(FWVERSION).text('');
        			if(item.hasOwnProperty('device_wwn'))
					{
						$(WWN).text(item.device_wwn);
						$(WWN_FORM_ITEM).show();
					}
					else
					{	
						$(WWN).text('');
						$(WWN_FORM_ITEM).hide();
					}
					showAssociatedDevices(item);
        			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
        				$(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.node_state.match(/installdone/i) && item.node_status != 'No component(s) deployed.')
					{
                        $(INSTALL_LOGS).show();
                        $("#hpsum-switch-viewlogs a").addClass("company-a").text("View Log");
                    } 
					$(GROUP).text('');
					if(item.hasOwnProperty('group_name')) {
						if( item.group_name.length == 0) {
							$(GROUP).text('none');
						}
						else {
							for(var iter=0 ; iter<item.group_name.length ; iter++)
							{
								var group_uri = '#/group/show/overview/r/session/'+ item.node_session + '/node/group/' + item.groups[iter]+'/getdata';
								
								//Code changes for placement. The code needs some spacing before the individual groups are appended.
								var uri = '<a href="'+group_uri+'" class="company-a">' +item.group_name[iter].group_name+ '</a>' ;
								if(iter == 0) {
									$(GROUP).append(uri);
								}
								else
								{
									$(GROUP).append('&nbsp;&nbsp;' + uri);
								}
									
							}
						}
					}
					else {
					    $(GROUP).text('none');
					}
        		}
            }
            
            function showAssociatedDevices(item){
				$(NOASSOC).show();
				$(PARTNER).html('');
				
				if(item.type == "sas_switch")
				{
					if(item.oa_ip_address)
					{
						$(NOASSOC).hide();
						$(ASSOC).show();
						var assoc_node_url = '#/node/show/r/session/' + session.getToken() + '/node/' + item.assoc_node_id + '/getData';
						if(item.assoc_node_id)
						{
							var assoc_node_url = '#/node/show/r/session/' + session.getToken() +'/node/' + item.assoc_node_id + '/getdata';
							$(OA).html ('<a href="' + assoc_node_url + '">' + item.oa_ip_address+ '</a>');
						}
						else if(item.ass_oa_id)
						{
							var assoc_node_url = '#/node/show/r/session/' + session.getToken() +'/node/' + item.ass_oa_id + '/getdata';
							$(OA).html ('<a href="' + assoc_node_url + '">' + item.oa_ip_address+ '</a>');
						}
						else
						{
							$(OA).text(item.oa_ip_address);
						}
					}
					if(item.partner_ip_address)
					{
						if(item.partner_node_id)
						{
							var partner_url = '#/node/show/r/session/' + session.getToken() +'/node/' + item.partener_node_id + '/getdata';
							$(PARTNERIP).html ('<a href="' + partner_url + '">' + item.partner_ip_address+ '</a>');					
						}
						else
						{
							$(PARTNERIP).text(item.partner_ip_address);
						}
						$(PARTNERWFW).text(item.partner_written_version);
						$(PARTNERAFW).text(item.partner_active_version);
					}
				}
				
				else if ( item.auto_add_assoc_nodes == true )
				{
					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;
							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;
							$(NOASSOC).hide();
							var tablecontents1 = "<table><tr> <td> <u>" + localizer.getString('hpsum.enclosure.deviceType') + "</u> </td> <td> <u>" + localizer.getString('hpsum.common.ipDns') + "</u> </td></tr>";
							for(var i=0; i<nodeAssoData.node.length; i++)
							{
								if(nodeAssoData.node[i].node_id)
								{
									var assoc_node_url = '#/node/show/r/session/' + session.getToken() +'/node/'+ nodeAssoData.node[i].node_id+'/getData';
									tablecontents1 += "<tr><td>" + nodeAssoData.node[i].type +' '+ nodeAssoData.node[i].productName
										+'</td><td>' + '<a href= "' + assoc_node_url + '">' +nodeAssoData.node[i].ip_or_dns+'</a>' + '</td></tr>';
								}
								else
								{
									tablecontents1 += "<tr><td>" + nodeAssoData.node[i].type +' '+nodeAssoData.node[i].productName
									+'</td><td>' + nodeAssoData.node[i].ip_or_dns + '</td></tr>';
								}
							}
							tablecontents1 += "</table>";
							$(PARTNER).html(tablecontents1);
							
						},
						error : function(errorInfo){ }
					});
				}
            }
            
            function onItemError(error) {
                $(ROOT).append(noItem);
            }

            function onItemError(errorMessage) {
            }
            
            function onResize() {
                var connectivity = $('#tour-switch-connectivity');
                if (connectivity.width() < 700 || connectivity.height() < 300) {
                    $('.hp-overview-graphic .hp-form-section > .hp-switch').show();
                    $('.hp-overview-graphic .hp-form-section > .hp-switch-context').hide();
                } else {
                    $('.hp-overview-graphic .hp-form-section > .hp-switch').hide();
                    $('.hp-overview-graphic .hp-form-section > .hp-switch-context').show();
                }
            }

            function onSelectionChange(selection) {
                urlFragment.replaceHrefUris(ROOT, selection.uris);
                if ($(ROOT).hasClass('hp-show-init')) {
                    $(ROOT).removeClass('hp-show-init');
                } else {
                    $('#tour-server-bundle-item').addClass('hp-show-changing');
                }
            }
          
            /**
             * @public
             */
            this.pause = function () {
                //$(window).off('resize', onResize);
                presenter.off("selectionChange", onSelectionChange);
                presenter.off("itemChange", onItemChange);
                presenter.off("itemError", onItemError);
            };
            
            this.resume = function () {
                $('.hp-grid-panels').hpGridPanels('reset');
                presenter.on("selectionChange", onSelectionChange);
                presenter.on("itemChange", onItemChange);
                presenter.on("itemError", onItemError);
                //$(window).on('resize', onResize);
                //onResize();
            };
            
            this.init = function() {
            	if(!presenter.initialized())
            		presenter.init();
                noItem = $(noneHtml);
                $('.hp-grid-panels').hpGridPanels();
                
                this.resume();
            };
            
        }

        return new SwitchOverviewView();
    }());
    
    return SwitchOverviewView;
});
