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

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

    var IpduOverviewView = (function() {
      
        var ROOT = '#hpsum-ipdu-show-overview';
        var PANELS = '.hp-grid-panels',
        	DESCRIPTION = '#hpsum-node-description',
        	BASELINE='#hpsum-node-bundle',
			ADDPACKAGE = '#hpsum-node-additional-bundle',
        	PAIRED = '#hpsum-ipdu-paired',
        	CORES ='#hpsum-ipdu-cores',
        	COREDETAILS = '#hpsum-ipdu-coredetails',
        	EXTBARDETAILS = '#hpsum-ipdu-extbars-details',
        	NOEXTBAR = '#hpsum-ipdu-no-extbars',
        	SPINNER = '#hpsum-node-progress-spinner',
            INSTALL_LOGS = '#hpsum-ipdu-install-log',
			EDIT_GENERAL = '#hpsum-ipdu-general-edit';
      
        /**
         * Constructor
         */
        function IpduOverviewView() {
          
            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')), "ipdu 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-ipdu-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.partner_available == undefined)
        				$(PAIRED).text('');
        			else {
        				if(item.partner_available == true)
        				{
        					if(item.partner_ip_address_ipv4 == '')
        						$(PAIRED).text(item.partner_ip_address_ipv6);
        					else
        						$(PAIRED).text(item.partner_ip_address_ipv4);
							$('#hpsum-ipdu-no-assoc').hide();
        				}
        				else
        					$(PAIRED).text('');
        			}
        			showCoreDetails(item);
        			showExtBarDetails(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)){
                        $(INSTALL_LOGS).show();
                        $("#hpsum-ipdu-viewlogs a").addClass("company-a").text("View Log");
                    }  

        		}
                $(PANELS).hpGridPanels('reset');
                $(ROOT).removeClass('hp-show-changing');
                $('.hp-dynamic', ROOT).removeClass('hp-unavailable');
				$('#hpsum-node-bundle').css('opacity','1.0');
            }
            
            function showCoreDetails(item){
            	if(item.cores == undefined)
            		return;
            	if(item.cores.length == 0)
            		return;
				$(CORES).text(item.cores.length);
            	var i,htmlContents="";
            	for(i=0; i<item.cores.length; i++){
            	    htmlContents += '<label>' + localizer.getString('hpsum.common.core') + ' + (i+1) +' +':</label>';
            	    htmlContents += '<ol><li style="margin-bottom: 5px;padding-left:10px;">' + localizer.getString('hpsum.common.model') +': <label style="padding-left:115px;">'+ item.cores[i].model_id +'</label></li>' ;
            	    htmlContents += '<li style="margin-bottom: 5px;padding-left:10px;">' + localizer.getString('hpsum.moonshot.productID') + ': <label style="padding-left:90px;">'+ item.cores[i].product_id +'</label></li>' ;
            	    htmlContents += '<li style="margin-bottom: 5px;padding-left:10px;">' + localizer.getString('hpsum.common.firmwareVersion') + ': <label style="padding-left:50px;">'+ item.cores[i].version +'</label></li>' ;
            	    htmlContents += '<li style="margin-bottom: 5px;padding-left:10px;">' + localizer.getString('hpsum.common.state') + ': <label style="padding-left:120px;">'+ item.cores[i].state +'</label></li>' ;
            		htmlContents += '</ol>';
            	}
            	$(COREDETAILS).html(htmlContents);
            	$('.hp-collapsible').hpCollapsible();
				//$('.hp-collapsible').hpCollapsible('expand');
            }
            
            function showExtBarDetails(item){
            	if(item.cores == undefined)
            		return;
            	if(item.cores.length == 0)
            		return;
            	var i,j,contents="";
            	$(NOEXTBAR).hide();
            	for(i=0; i<item.cores.length; i++){
            		var htmlContents="";
            		htmlContents += '<div class="hp-collapsible"><label>' + localizer.getString('hpsum.common.core') + (i+1) +':</label> <div>';
            		htmlContents += '<table><tr> <td> ' + localizer.getString('hpsum.moonshot.productID') +' </td> <td> ' + localizer.getString('hpsum.common.model') +'</td> <td> ' + localizer.getString('hpsum.common.version') +'</td></tr> ';
            		if(item.cores[i].extbars.length == 0){
            		    htmlContents += '<tr><td>' + localizer.getString('hpsum.ipdu.noExtBars') + '</td></tr> </table> </div>';
            			contents += htmlContents;
            			htmlContents='';
            			continue;
            		}
            		for(j=0; j<item.cores[i].extbars.length; j++){
            			htmlContents += '<tr> <td>' + item.cores[i].extbars[j].product_id + '</td> <td>'
            									+  item.cores[i].extbars[j].model_id +'</td> <td>' 
            									+ item.cores[i].extbars[j].version + '</td></tr>';	
            		}
            		htmlContents += '</table></div>';
					contents += htmlContents ;	
            	}
            	
            	$(EXTBARDETAILS).html(contents);
            	$('.hp-collapsible').hpCollapsible();
				$('.hp-collapsible').hpCollapsible('expand');
            }          
            
            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');
                    $('#hpsum-node-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 IpduOverviewView();
    }());
    
    return IpduOverviewView;
});
