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

    var sdflexOverviewView = (function() {
      
        var ROOT = '#hpsum-sdflex-show-overview';
        var PANELS = '.hp-grid-panels',
            MODEL = '#hpsum-sdflex-model',
        	SYSTEM_NAME = '#hpsum-sdflex-system-name',
        	FIRMWARE_NAME = '#hpsum-sdflex-firmware-name',
            FIRMWARE_VERSION = '#hpsum-sdflex-firmware-version',
            FIRMWARE_HEALTH = '#hpsum-sdflex-firmware-health',
            SERIAL_NUMBER = '#hpsum-sdflex-serial-number',
            UUID = '#hpsum-sdflex-uuid',
            BASELINE='#hpsum-sdflex-baseline',
			ADDPACKAGE = '#hpsum-sdflex-additional-bundle',
        	SPINNER = '#hpsum-node-add-spinner',
            INSTALL_LOGS = '#hpsum-sdflex-install-log',
            GROUP = '#hpsum-server-group',
            DEVICES = '#hpsum-sdflex-devices',
			EDIT_GENERAL = '#hpsum-sdflex-general-edit';
        
      
        /**
         * Constructor
         */
        function sdflexOverviewView() {
          
            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')), "sdflex 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-sdflex-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');     			
        			$(MODEL).text(item.model);
                    $(SYSTEM_NAME).text(item.system_name);
        			      				
        			if(item.hasOwnProperty('firmware_version')){
        				$(FIRMWARE_VERSION).text(item.firmware_version);
		 			}
        			else{
        				$(FIRMWARE_VERSION).text('');
        			}
        			                 
                    if(item.hasOwnProperty('firmware_name'))
                        $(FIRMWARE_NAME).text(item.firmware_name);
                    else
                        $(FIRMWARE_NAME).text("");

                    if(item.hasOwnProperty('firmware_health'))
                        $(FIRMWARE_HEALTH).text(item.firmware_health);
                    else
                        $(FIRMWARE_HEALTH).text("");
                    
                    if(item.hasOwnProperty('serial_number'))
                        $(SERIAL_NUMBER).text(item.serial_number);
                    else
                        $(SERIAL_NUMBER).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-sdflex-viewlogs a").addClass("company-a").text("View Log");
                    }  
                    
                    // show partition information
                    var partitionSection;
                    $(DEVICES).html('');
                    if (item.hasOwnProperty('sdflex_npar_list') && item.sdflex_npar_list.length > 0) {
                        partitionSection = $('<div></div>').addClass('hp-collapsible sdflex-section-title').html('<label>'+ localizer.getString('hpsum.sdflex.partitions') +'</label>');
                        var partitionDiv = $('<div></div>');

                        var device_table = $('<table></table>');
                        var hdr_row = $('<thead></thead>');
                        hdr_row.append('<tr><td><div class=\"hp-status"></div></td><td>'+localizer.getString('hpsum.sdflex.number')+
                        '</td><td>'+localizer.getString('hpsum.common.power')+'</td><td>'+localizer.getString('hpsum.common.healthStatus')+
                        '</td><td>'+localizer.getString('hpsum.sdflex.activeFirmware')+'</td><td>'+localizer.getString('hpsum.sdflex.nextFirmware')+'</td></tr>');
                        device_table.append(hdr_row);

                        for (var i = 0; i < item.sdflex_npar_list.length; i++) {
                            var device = item.sdflex_npar_list[i];
                            var parHealth = '';
                            var installedFW = ''; 
                            var nextFW = '';
                            var par_name = '';
                            
                            par_name = device.sdflex_npar_fw_info.Name;
                            parHealth = device.sdflex_npar_fw_info.Status.Health;
                            
                            installedFW = device.sdflex_npar_fw_info.Version;
                            var hasPendingFw = false;
                            hasPendingFw = device.HasPendingFw;
                            
                            var parstatus = '';
                            if (hasPendingFw) {
                                nextFW = device.sdflex_npar_fw_next_info.Version;
                                parstatus = '<div title=\"Mismatch\" class=\"hp-status hp-status-warning\"></div>';
                            } else {
                                nextFW = "NA";
                                parstatus = '<div class=\"hp-status hp-status-ok\"></div>';
                            }
                            var par_number = device.npar_num;
                            var power_state = device.PowerState;    
                            var dev_row = $('<tr></tr>').html('<td>' + parstatus + '</td><td>' + par_number + '</td><td>' + power_state + '</td><td>' + parHealth + '</td><td>' + installedFW + '</td><td>' + nextFW + '</td>');
                            device_table.append(dev_row);

                            var hasDetails = false;
                            var details_row = $('<tr></tr>').addClass('hp-row-details-row');
                            var details_cell = $('<td colspan=\"7\"></td>').addClass('hp-row-details-cell');

                            details_row.append(details_cell);
                            device_table.append(details_row);
                        }

                        partitionDiv.append(device_table);
                        partitionSection.append(partitionDiv);
                        
                        $(DEVICES).append(partitionSection);
                        $(DEVICES + ' .hp-collapsible').hpCollapsible();
                        $(DEVICES + ' .sdflex-section-title').removeClass('hp-collapsed');
                    }
                   
        		}
				$(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');
                $('#hpsum-warning-messages').hpsumWarnings(item, false);
            }
            
            function getNodeStatus(item){
            	  var sdflextimer = setInterval(function () {
            		
            		presenter.getNodeStatus(item, {
                				success : function(data) {
                    				onsdflexStatusSuccess(data,sdflextimer);
                    		 	},
                    			error : function(errorInfo) {
                        			onNodeStatusError(errorInfo,sdflextimer);
                    			}
                			});
                			
                }, 3000);
            }
            
            function onsdflexStatusSuccess(data,sdflextimer){
            	if(thisNode.node_id == data.hapi.node_status.node_id) {
            		if(!data.hapi.node_status.node_phase.match(/initialize/i)){
        				clearInterval(sdflextimer);
        				sdflextimer = 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');
                }
            }
          
            /**
             * @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 sdflexOverviewView();
    }());
    
    return sdflexOverviewView;
});
