// (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 VcOverviewView = (function() {
      
        var ROOT = '#hpsum-vc-show-overview';
        var PANELS = '.hp-grid-panels',
        	DESCRIPTION = '#hpsum-vc-description',
        	TYPE ='#hpsum-vc-type',
        	BASELINE='#hpsum-vc-bundle',
			ADDPACKAGE = '#hpsum-vc-additional-bundle',
        	VCDOMAIN='#hpsum-vc-domain',
        	OA = '#hpsum-vc-oa',
			ASSOC_DEVICES = '#hpsum-vc-assocdevices',
        	NO_ASSOC_DEVICES ='#hpsum-vc-no-devices',
        	INSTALLEDROM ='#hpsum-vc-installed-rom',
        	HEALTHSTATUS = '#hpsum-vc-health-status',
        	MATRIXENABLED = '#hpsum-vc-matrix-enabled',
        	MATRIXVERSION = '#hpsum-vc-matrix-version',
			ROLLBACKSUPPORTED = '#hpsum-vc-rollback-supported',
			ROLLBACKVERSION = '#hpsum-vc-rollback-version',
			GROUP = '#hpsum-server-group',
        	SPINNER = '#hpsum-node-add-spinner',
            INSTALL_LOGS = '#hpsum-vc-install-log',
			EDIT_GENERAL = '#hpsum-vc-general-edit';
      
        /**
         * Constructor
         */
        function VcOverviewView() {
          
            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').css("display", "block");
        		
                if(!item.type.match(/virtual_connect/i)) {
                    if(router.location().indexOf("/node") == 0)             
                        router.go((urlFragment.replaceView(router.location(), 'show/' + item.type + '/overview')), "vc show overview");
                    else {
                        $(ROOT).closest('section').css("display", "none");
                        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-vc-install-log 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();
					$(NO_ASSOC_DEVICES).hide();
					$(ASSOC_DEVICES).hide();
        			$('.hp-grid-panels').css({"display":""});
        			$('.hp-grid-panels').hpGridPanels('reset');     			
        			$(DESCRIPTION).text(item.description);
        			if(item.hasOwnProperty('vc_domain'))
        				$(VCDOMAIN).text(item.vc_domain);
        			else 
        				$(VCDOMAIN).text('');
        			if(item.hasOwnProperty('vc_installed_version')){
						$(NO_ASSOC_DEVICES).hide();
						$(ASSOC_DEVICES).show();
        				$(INSTALLEDROM).text(item.vc_installed_version);
        				$(HEALTHSTATUS).text(item.health_status);
						$(ROLLBACKSUPPORTED).text(item.rollback_supported);
						$(ROLLBACKVERSION).text(item.rollback_version);
						var separator,nodeIp;
						if(item.oa_address && item.oa_aliasaddress)
							separator =" / ";
						else
							separator="";
						if(item.oa_address.indexOf(":")>0)
							nodeIp = item.oa_aliasaddress +separator+ item.oa_address;
						else
							nodeIp = item.oa_address +separator+ item.oa_aliasaddress;
						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 + '" class="company-a">' + nodeIp + '</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 + '" class="company-a">' + nodeIp + '</a>');
						}
        				else{
							$(OA).text(nodeIp);
        				}
        			}
        			else{
        				$(INSTALLEDROM).text('');
        				$(HEALTHSTATUS).text('');
						$(ROLLBACKSUPPORTED).text('');
						$(ROLLBACKVERSION).text('');
						$(NO_ASSOC_DEVICES).show();
        				$(ASSOC_DEVICES).hide();
        			}
        			showVCModules(item);
        			if(item.alt_name == undefined)
        				$(TYPE).text(item.type);
        			else
        				$(TYPE).text(item.alt_name);
        			
        			$(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');
        			}
					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-vc-install-log a").addClass("company-a").text("View Log");
                    }

        		}
                $(PANELS).hpGridPanels('reset');
                $(ROOT).removeClass('hp-show-changing');
                $('.hp-dynamic', ROOT).removeClass('hp-unavailable');
            }
            
            function showVCModules(item){
            	if(item.devices === undefined)
            		return;
            	if(item.devices.device === undefined)
            		return;
            		
                $("#hpsum-vc-modules-table > tbody > tr").remove();
                $("#hpsum-vc-modules-table_filter").remove();
                $("#hpsum-vc-modules-table_processing").remove();
                var modulesTable = initModulesTable();
                modulesTable.fnClearTable();
            		 
            	var i;
            	for ( i=0; i<item.devices.device.length; i++){
            		var tableItem = [{
            						devicenumber: item.devices.device[i].devicenumber,
            						enclosure: item.devices.device[i].enclosure,
            						type: item.devices.device[i].product_id,
            						active_version : item.devices.device[i].fw_item.active_version,
            						version: item.devices.device[i].fw_item.version,
            						health_status : item.devices.device[i].fw_item.health_status
            					}];
            		modulesTable.fnAddData(tableItem);
            	}
            }
            
            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 initModulesTable() {
                return $('#hpsum-vc-modules-table').dataTable({
                        oLanguage: {
                            sEmptyTable: localizer.getString('hpsum.node.noItemsFound'),
                            sSearch: localizer.getString('hpsum.common.search')
                               },
                    bPaginate : false,
                    bProcessing : true,
                    bFilter : true,
                    bSort : true,
                    bAutoWidth : true,
                    bInfo : false,
                    bRetrieve : false,
                    bDestroy : true,
                        aoColumns : [
                            {mDataProp: 'devicenumber'},
                            {mDataProp: 'enclosure'},
                            {mDataProp: 'type'},
                            {mDataProp: 'active_version'},
                            {mDataProp: 'version'},
                            {mDataProp: 'health_status'}
                            ],
                    aaSorting: [[ 0, "asc" ]],
                    });                
            }
          
            /**
             * @public
             */
            this.resume = function() {
                $(ROOT).closest('section').css("display", "block");
                $(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 VcOverviewView;
    }());
    
    return new VcOverviewView;
});
