// (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/model/Session',
    'jquery',
    'hp/lib/jquery.hpGridPanels'],
function(presenter, urlFragment,router, linkTargetBuilder, noneHtml, localizer, session) { "use strict";

    var moonshotOverviewView = (function() {
      
        var ROOT = '#hpsum-moonshot-show-overview';
        var PANELS = '.hp-grid-panels',
        	DESCRIPTION = '#hpsum-moonshot-description',
        	BASELINE='#hpsum-moonshot-baseline',
			ADDPACKAGE = '#hpsum-moonshot-additional-bundle',
        	SPINNER = '#hpsum-node-add-spinner',
            INSTALL_LOGS = '#hpsum-moonshot-install-log',
            CHASSIS_NAME = '#hpsum-moonshot-chassis-name',
            PRODUCT_NAME = '#hpsum-moonshot-product-name',
            PRODUCT_ID = '#hpsum-moonshot-product-id',
            UUID = '#hpsum-moonshot-uuid',
			GROUP = '#hpsum-server-group',
            SERIAL_NUMBER = '#hpsum-moonshot-serial-no',
            BUNDLE_VERSION = '#hpsum-moonshot-bundle-version',
			SWITCH_BUNDLE_VERSION = '#hpsum-moonshot-switch-bundle-version',
            SWITCH_TABLE = '#hpsum-moonshot-switch-table',
            CARTRIDGE_TABLE = '#hpsum-moonshot-cartridge-table',
			EDIT_GENERAL = '#hpsum-moonshot-general-edit';
            
      
        /**
         * Constructor
         */
        function moonshotOverviewView() {
          
            var noItem;
            var timer= null;
            var 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')), "moonshot 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-moonshot-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();
					$('.hp-grid-panels').css({"display":""});
        			$('.hp-grid-panels').hpGridPanels('reset');     			
        			$(DESCRIPTION).text(item.description);
        			      				
        			if(item.hasOwnProperty('bundle_version')){
        				$(BUNDLE_VERSION).text(item.bundle_version);
						showCartridges(item);					
        			}
        			else{
        				$(BUNDLE_VERSION).text('');
        				$(CARTRIDGE_TABLE).hide();
        			}
        			
					if(item.hasOwnProperty('switch_bundle_version')){
        				$(SWITCH_BUNDLE_VERSION).text(item.switch_bundle_version);
						showSwitches(item);						
        			}
        			else{
        				$(SWITCH_BUNDLE_VERSION).text('');
        				$(SWITCH_TABLE).hide();
        			}
					
                    if(item.hasOwnProperty('serial_number'))
                        $(SERIAL_NUMBER).text(item.serial_number);
                    else 
                        $(SERIAL_NUMBER).text('');
                        
                    if(item.hasOwnProperty('product_id'))
                        $(PRODUCT_ID).text(item.product_id);
                    else
                        $(PRODUCT_ID).text("");
                        
                    if(item.hasOwnProperty('product_name'))
                        $(PRODUCT_NAME).text(item.product_name);
                    else
                        $(PRODUCT_NAME).text("");
                        
                    if(item.hasOwnProperty('chassis_name'))
                        $(CHASSIS_NAME).text(item.chassis_name);
                    else
                        $(CHASSIS_NAME).text("");
                        
                    if(item.hasOwnProperty('uuid'))
                        $(UUID).text(item.uuid);
                    else
                        $(UUID).text("");
        			
        			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)){
                        $(INSTALL_LOGS).show();
                        $("#hpsum-moonshot-viewlogs a").addClass("company-a").text("View Log");
                    }  

        		}
				$(GROUP).text('');
				if (item.hasOwnProperty('group_name') && item.hasOwnProperty('group')) {
        			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');
        		}
                $(PANELS).hpGridPanels('reset');
                $(ROOT).removeClass('hp-show-changing');
                $('.hp-dynamic', ROOT).removeClass('hp-unavailable');
            }
            
			function showSwitches(item) {    
                if(item.switch_info_list.length > 0) {
                    $('#hpsum-moonshot-no-switches').hide();
                    $(SWITCH_TABLE).show();
                    
                    $("#hpsum-moonshot-switch-table > tbody > tr").remove();
                    $("#hpsum-moonshot-switch-table_filter").remove();
                    $("#hpsum-moonshot-switch-table_processing").remove();
                    var switchTable = initSwitchTable();
                    switchTable.fnClearTable();
                    switchTable.fnAddData(item.switch_info_list);
                } else {
                    $(SWITCH_TABLE).hide();
                    $('#hpsum-moonshot-no-switches').show();
                }	
            }
            
            function showCartridges(item) {
                if(item.cartridge_info_list.length > 0) {
                    $(CARTRIDGE_TABLE).show();
                    $('#hpsum-moonshot-no-cartridges').hide();
                    
                    $("#hpsum-moonshot-cartridge-table > tbody > tr").remove();
                    $("#hpsum-moonshot-cartridge-table_filter").remove();
                    $("#hpsum-moonshot-cartridge-table_processing").remove();
                    var cartridgeTable = initCartridgeTable();
                    cartridgeTable.fnClearTable();
                    cartridgeTable.fnAddData(item.cartridge_info_list);
                } else {
                    $(CARTRIDGE_TABLE).hide();
                    $('#hpsum-moonshot-no-cartridges').show();
                }
            }
			
            function getNodeStatus(item){
            	  var moonshottimer = setInterval(function () {
            		
            		presenter.getNodeStatus(item, {
                				success : function(data) {
                    				onmoonshotStatusSuccess(data,moonshottimer);
                    		 	},
                    			error : function(errorInfo) {
                        			onNodeStatusError(errorInfo,moonshottimer);
                    			}
                			});
                			
                }, 3000);
            }
            
            function onmoonshotStatusSuccess(data,moonshottimer){
            	if(thisNode.node_id == data.hapi.node_status.node_id) {
            		if(!data.hapi.node_status.node_phase.match(/initialize/i)){
        				clearInterval(moonshottimer);
        				moonshottimer = 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 initSwitchTable() {
               return $(SWITCH_TABLE).dataTable({
                    bPaginate : false,
                    bFilter : false,
                    bInfo : false,
                    bAutoWidth : false,
                    bRetrieve : false,
                    bDestroy : true,
                    aoColumns : [
                        {mDataProp: 'slot'},
                        {mDataProp: 'product_name', sWidth: 200},
                        {mDataProp: 'serial_number'},
                        {mDataProp: 'power'},
                        {mDataProp: 'status'}],
                    aaSorting: [],
                    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                        return nRow;
                    }
                });
            }
            
            function initCartridgeTable() {
               return $(CARTRIDGE_TABLE).dataTable({
                    bPaginate : false,
                    bFilter : false,
                    bInfo : false,
                    bAutoWidth : false,
                    bRetrieve : false,
                    bDestroy : true,
                    aoColumns : [
                        {mDataProp: 'slot'},
                        {mDataProp: 'id'},
                        {mDataProp: 'product_name', sWidth: 200},
                        {mDataProp: 'serial_number'},
                        {mDataProp: 'power'},
                        {mDataProp: 'status'}],
                    aaSorting: [],
                    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                        return nRow;
                    }
                });
            }
          
            /**
             * @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);
            };
             
            this.init = function() {
            	if(!presenter.initialized())
            		presenter.init();
                noItem = $(noneHtml);
                $(PANELS).hpGridPanels();
                this.resume();
            };
        }

        return new moonshotOverviewView();
    }());
    
    return moonshotOverviewView;
});
