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

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

    var IntegrityIloOverView = (function() {
      
        var ROOT = '#hpsum-integrityilo-show-overview';
        var PANELS = '.hp-grid-panels',
        	DESCRIPTION = '#hpsum-integrityilo-description',
            TYPE = '#hpsum-integrityilo-type',
            PRODUCTNAME = '#hpsum-integrityilo-prodName',
        	PRODUCTID ='#hpsum-integrityilo-productid',
        	BASELINE='#hpsum-integrityilo-bundle',
			ADDPACKAGE = '#hpsum-integrityilo-additional-bundle',
        	SERIALNO='#hpsum-integrityilo-serialno',
        	OA = '#hpsum-integrityilo-oa',
			ASSOC_DEVICES = '#hpsum-integrityilo-assocdevices',
			NO_ASSOC_DEVICES = '#hpsum-integrityilo-no-devices',
        	INSTALLEDROM ='#hpsum-integrityilo-installed-rom',
        	MATRIXENABLED = '#hpsum-integrityilo-matrix-enabled',
        	MATRIXVERSION = '#hpsum-integrityilo-matrix-version',
			GROUP = '#hpsum-server-group',
        	SPINNER = '#hpsum-node-add-spinner',
            FWDETAILS = '#hpsum-integrityilo-fwdetails',
            FWDETAILSTABLE = '#hpsum-integrityilo-fwdetails-table',
            PARS ='#hpsum-integrityilo-assoc-pars',
            INSTALL_LOGS = '#hpsum-integrityilo-install-log',
			EDIT_GENERAL = '#hpsum-integrityilo-general-edit';
      
        /**
         * Constructor
         */
        function IntegrityIloOverView() {
          
            var noItem;
            
            function onItemChange(item) {
            	item = item.hapi;
                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')), "integrityilo 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-integrityilo-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();
					$(NO_ASSOC_DEVICES).hide();
					$(ASSOC_DEVICES).hide();
        			$('.hp-grid-panels').css({"display":""});
        			$('.hp-grid-panels').hpGridPanels('reset'); 

                    $(DESCRIPTION).text(item.description);

                    if(item.type === 'integrityilo3') 
                    {
                        $(TYPE).text("HP Integrity iLO 3");
                    } 
                    else
                    {
                        $(TYPE).text("HP Integrity iLO 2");
                    }

        			if(item.hasOwnProperty('serial_number'))
        			{
                        $(SERIALNO).text(item.serial_number);
                    }
        			else 
                    {
        				$(SERIALNO).text('');
                    }

        			if(item.hasOwnProperty('version'))
                    {
						$(NO_ASSOC_DEVICES).hide();
						$(ASSOC_DEVICES).show();
                        $(PRODUCTNAME).text(item.product_name);
                        $(FWDETAILS).text(item.version);
                        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
        					$(OA).text(item.oa_ip_address);
                        if(item.hasOwnProperty('is_ilo_domain') && item.is_ilo_domain) {
                        	$(PARS).closest('ol').show();
                        	var assoc_par = '';
                        	for(var n=0; n<item.domain_partitions.length; n++){
                        		var par = item.domain_partitions[n];
                        		if(par.monarchIP != item.ip) {
                        			assoc_par += '<p>'+ par.monarchIP + '</p>';
                        		}
                        	}                       	
                        	$(PARS).html(assoc_par);
                        } else {
                        	$(PARS).closest('ol').hide();
                        }
                        $(PRODUCTID).text(item.device_id);
                        $('.hp-collapsible label').css({'font-size': '13px'});
                        $('.hp-collapsible label').css({'margin-top': '0px'});
                        $('.hp-collapsible label').css({'margin-bottom': '0px'});
                        
                        $(FWDETAILSTABLE).html('');

                        if(item.fw_mismatch) 
                        {
                            //Create the fw mismatch tables
                            var iloVer = new Array();
                            var sfwVer = new Array();
                            var fpgaVer = new Array();
                            var monVer = new Array();
                            var bayNo = new Array();
                            var cnt;

                            var iloDetails = item.ilo_version.split(";");
                            var sfwDetails = item.sfw_version.split(";");
                            var fpgaDetails = item.fpga_version.split(";");
                            var monDetails = item.mon_version.split(";");
                            var bayCount = iloDetails.length - 1;

                            for(cnt = 0; cnt < bayCount; ++cnt) {
                                var bayInfo = iloDetails[cnt].split(":");
                                bayNo[cnt] = bayInfo[0];
                                iloVer[cnt] = bayInfo[1];

                                bayInfo = sfwDetails[cnt].split(":");
                                sfwVer[cnt] = bayInfo[1];

                                bayInfo = fpgaDetails[cnt].split(":");
                                fpgaVer[cnt] = bayInfo[1];

                                bayInfo = monDetails[cnt].split(":");
                                monVer[cnt] = bayInfo[1];
                            }
                            
                            var hdr_row, ilo_row, sfw_row, fpga_row, mon_row;
                                               
                            if(bayCount == 4) 
                            {
                            	hdr_row = $('<thead></thead>').html('<tr><td style=\"width:150px\">Type</td><td>'+bayNo[0]+'</td><td>'+bayNo[1]+'</td><td>'+bayNo[2]+'</td><td>'+bayNo[3]+'</td></tr>');
                            	ilo_row = $('<tr></tr>').html('<td>iLO FW</td><td>'+iloVer[0]+'</td><td>'+iloVer[1]+'</td><td>'+iloVer[2]+'</td><td>'+iloVer[3]+'</td>');
                            	sfw_row = $('<tr></tr>').html('<td>System FW</td><td>'+sfwVer[0]+'</td><td>'+sfwVer[1]+'</td><td>'+sfwVer[2]+'</td><td>'+sfwVer[3]+'</td>');
                            	fpga_row = $('<tr></tr>').html('<td>FPGA FW</td><td>'+fpgaVer[0]+'</td><td>'+fpgaVer[1]+'</td><td>'+fpgaVer[2]+'</td><td>'+fpgaVer[3]+'</td>');
                            	mon_row = $('<tr></tr>').html('<td>Power monitor FW</td><td>'+monVer[0]+'</td><td>'+monVer[1]+'</td><td>'+monVer[2]+'</td><td>'+monVer[3]+'</td>');   
                            } 
                            else if (bayCount == 2) 
                            {
                            	hdr_row = $('<thead></thead>').html('<tr><td style=\"width:150px\">Type</td><td>'+bayNo[0]+'</td><td>'+bayNo[1]+'</td></tr>');
                            	ilo_row = $('<tr></tr>').html('<td>iLO FW</td><td>'+iloVer[0]+'</td><td>'+iloVer[1]+'</td>');
                            	sfw_row = $('<tr></tr>').html('<td>System FW</td><td>'+sfwVer[0]+'</td><td>'+sfwVer[1]+'</td>');
                            	fpga_row = $('<tr></tr>').html('<td>FPGA FW</td><td>'+fpgaVer[0]+'</td><td>'+fpgaVer[1]+'</td>');
                            	mon_row = $('<tr></tr>').html('<td>Power monitor FW</td><td>'+monVer[0]+'</td><td>'+monVer[1]+'</td>');
                            }
                        } 
                        else 
                        {
                            //No mismatch only display the common fw version
                            hdr_row = $('<thead></thead>').html('<tr><td style=\"width:150px\">Type</td><td>Version</td></tr>');
                            ilo_row = $('<tr></tr>').html('<td>iLO FW</td><td>'+item.ilo_version+'</td>');
                            sfw_row = $('<tr></tr>').html('<td>System FW</td><td>'+item.sfw_version+'</td>');
                            fpga_row = $('<tr></tr>').html('<td>FPGA FW</td><td>'+item.fpga_version+'</td>');
                            mon_row = $('<tr></tr>').html('<td>Power monitor FW</td><td>'+item.mon_version+'</td>');                       
                        }
                        
                        $(FWDETAILSTABLE).append(hdr_row, ilo_row, sfw_row, fpga_row, mon_row);
        			}
        			else
                    {
        				$(FWDETAILS).text('');
        				$(NO_ASSOC_DEVICES).show();
						$(ASSOC_DEVICES).hide();
                        $(PRODUCTID).text('');
                        $(PRODUCTNAME).text('');
                        $(FWDETAILSTABLE).html('');
                        $(PARS).html('');
        			}
        			
        			$(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');
        			}
        			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-integrityilo-viewlogs a").addClass("company-a").text("View Log");
                    }  
        		}
                $(PANELS).hpGridPanels('reset');
                $(ROOT).removeClass('hp-show-changing');
                $('.hp-dynamic', ROOT).removeClass('hp-unavailable');
            }

            function isDataTable (nTable) {
                var settings = $.fn.dataTableSettings;
                for (var i=0, iLen=settings.length ; i<iLen ; i++) {
                    if (settings[i].nTable == nTable) {
                        return true;
                    }
                }
                return false;
            }
                        
            
            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();
                $(INSTALLEDROM).hpCollapsible();
                this.resume();
            };
        }

        return new IntegrityIloOverView();
    }());
    
    return IntegrityIloOverView;
});
