// (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!hpsumpages/graphics/enclosure.html', 
        'text!hpPages/core/no_details.html', 
        'jquery', 
        'hpsum/view/node/jquery.hpsumWarnings', 
        'hp/lib/jquery.hpGridPanels', 
        'hp/lib/jquery.hpEllipsis', 
        'hp/lib/jquery.hpStatus', 
        'hp/lib/jquery.hpCollapsible', 
        'hp/lib/jquery.hpUtilizationMeter'], 
function(presenter, urlFragment, router, localizer, linkTargetBuilder, enclosureGraphicHtml, noneHtml) {"use strict";

        var SD2ShowOverviewView = ( function() {

            var ROOT = '#hpsum-sd2-show-overview',
            PANELS = '.hp-grid-panels',
            BASELINE = '#hpsum-sd2-bundle', 
			ADDPACKAGE = '#hpsum-sd2-additional-bundle',
            FIRMWARE_VERSION = '#hpsum-sd2-fwversion', 
            CPLX_NAME = '#hpsum-sd2-cplx-name', 
            DEVICES = '#hpsum-sd2-devices', 
            SERIAL_NO = '#hpsum-sd2-serialno', 
			GROUP = '#hpsum-server-group',
            DESCRIPTION = '#hpsum-sd2-description',
            MODEL = '#hpsum-sd2-model',
            COMPLEX_FW = 0,
            PARTITION_FW = 2,
            INSTALLED_FW = 4,
            FW_MISMATCH = 1,
            INSTALL_LOGS = '#hpsum-sd2-install-log',
            ASSOC_DEVICES = '#hpsum-sd2-assocdevices',
            NO_ASSOC_DEVICES = '#hpsum-sd2-no-devices',
            ASSOC_DEV_SECTION = '#hpsum-sd2-assocdev-sec',
			EDIT_GENERAL = '#hpsum-sd2-general-edit';
            
            var DEVICE_USCOREBLADE = 0,
            DEVICE_USCOREINTERCONNECT_USCORETRAY = 1,
            DEVICE_USCOREPOWER_USCORESUPPLY = 2,
            DEVICE_USCOREFAN = 3,
            DEVICE_USCOREOA = 4,
            DEVICE_USCORELCD = 5,
            DEVICE_USCOREENCLOSURE = 6,
            DEVICE_USCOREINTERPOSER = 7,
            DEVICE_USCOREDVD = 8,
            DEVICE_USCOREGPSM = 9,
            DEVICE_USCOREXFM = 10,
            DEVICE_USCOREXIOX = 11;

            /**
             * Constructor
             */
            function SD2ShowOverviewView() {

                var noItem;

                function onItemChange(item) {
                    item = item.hapi;
                    noItem.remove();
                    $(ASSOC_DEV_SECTION).hide();
                    $(ASSOC_DEVICES).html('');
                    
                    item.type = item.type.toLowerCase();
                    var uitype = presenter.getUINodeType(item.type);
                    $(ROOT).closest('section').show();
                    
                    if(item.type == "oa") {
	        			if(!router.location().match(item.type))
	        				router.go((urlFragment.replaceView(router.location(), 'show/' + item.type + '/overview')));
        			}
                    
	        		if(!router.location().match(uitype)) {
	        		    if(router.location().indexOf("/node") == 0)
	        		      router.go((urlFragment.replaceView(router.location(), 'show/' + item.type + '/overview')), "sd2oa 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-sd2-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"
                        });
                        presenter.startNodeStatus(item);
                    } else {
                        $('.hp-grid-panels').css({
                            "display" : ""
                        });
                        $('.hp-grid-panels').hpGridPanels('reset');
                        $(DESCRIPTION).text(item.description);
						
						if(item.type.match(/sdx/i))
									$(MODEL).text('HP Integrity Superdome X OA');
						else
									$(MODEL).text('HP Integrity Superdome 2 OA');
								
                        if(item.hasOwnProperty('is_dh_oa')){
                        	if(item.is_dh_oa){
                        		$(ASSOC_DEV_SECTION).show();
                        		populateAssociatedTargets(item);
                        	}
                        }
                        if (item.hasOwnProperty('firmware_version')) {
                            if (item.firmware_version == "*") {
                                $(FIRMWARE_VERSION).html('<div title=\"'+ localizer.getString('hpsum.sd2oa.mismatch') +'\" class=\"hp-status hp-status-warning\"></div><a id=cplx-fw-ver>' + localizer.getString('hpsum.sd2oa.mismatch') + '</a>');
                            } else if (item.firmware_mismatch) {
                                $(FIRMWARE_VERSION).html('<div title=\"'+ localizer.getString('hpsum.sd2oa.mismatch') +'\" class=\"hp-status hp-status-warning\"></div><a id=cplx-fw-ver>' + item.firmware_version + '</a>');
                                
                                if(item.complex_mismatch_list.length > 0) {
                                    $('#cplx-fw-ver').on('click', function(){
                                       $("<div></div>").dialog({
                                            buttons : {
                                                "Close" : function() {
                                                    $(this).dialog("close");
                                                }
                                            },
                                            close : function(event, ui) {
                                                $(this).remove();
                                            },
                                            resizable : false,
                                            title : localizer.getString('hpsum.sd2oa.cplxMismatchDetails'),
                                            width : 600,
                                            modal : true
                                        }).html(getComplexMismatchDetails(item));
                                    });
                                }
                            } else {
                                $(FIRMWARE_VERSION).text(item.firmware_version);
                            }
                            $(CPLX_NAME).text(item.complex_name);
                            $(SERIAL_NO).text(item.serial_number);

                            var partitionSection;
                            if (item.npar_list.length > 0) {
                                partitionSection = $('<div></div>').addClass('hp-collapsible sd2-section-title').html('<label>'+ localizer.getString('hpsum.sd2oa.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.sd2oa.number')+
                                '</td><td>'+localizer.getString('hpsum.common.name')+'</td><td>'+localizer.getString('hpsum.common.state')+
                                '</td><td>'+localizer.getString('hpsum.common.model')+'</td><td>'+localizer.getString('hpsum.sd2oa.installedFW')+
                                '</td><td>'+localizer.getString('hpsum.common.server')+'</td></tr>');
                                device_table.append(hdr_row);

                                for (var i = 0; i < item.npar_list.length; i++) {
                                    var device = item.npar_list[i];
                                    var parState, installedFW;
                                    if (device.Status === 0) {
                                        parState = 'Active';
                                    } else {
                                        parState = 'Inactive';
                                    }

                                    var hasMismatch = false;
                                    for (var j = 0; j < device.FWVersionEx.length; j++) {
                                        var fw = device.FWVersionEx[j];
                                        if (fw.FWVersionType == INSTALLED_FW) {
                                            installedFW = fw.FWVersion;
                                        }
                                        if (fw.FWMismatch == FW_MISMATCH) {
                                            hasMismatch = true;
                                        }
                                    }

                                    var parstatus = '';
                                    if (hasMismatch) {
                                        parstatus = '<div title=\"Mismatch\" class=\"hp-status hp-status-warning\"></div>';
                                    } else {
                                        parstatus = '<div class=\"hp-status hp-status-ok\"></div>';
                                    }

                                    var dev_row = $('<tr></tr>').html('<td>' + parstatus + '</td><td>' + device.Number + '</td><td>' + device.Name + '</td><td>' + parState + '</td><td>' + device.BladeName + '</td><td>' + installedFW + '</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');

                                    if (device.VParArray.VPar.length > 0 || device.Blades.Blade.length > 0) {
                                        hasDetails = true;
                                        //Add the details row for the partition
                                        if (device.VParArray.VPar.length > 0) {
                                            var vparSection = $('<div></div>').addClass('hp-collapsible').html('<label>'+localizer.getString('hpsum.sd2oa.vpars')+'</label>');
                                            var vparDiv = $('<div></div>');
                                            var vparTable = $('<table></table>');
                                            var vpar_hdr = $('<thead></thead>');
                                            vpar_hdr.append('<tr><td>'+localizer.getString('hpsum.sd2oa.number')+'</td><td>'+localizer.getString('hpsum.common.name')+'</td><td>'+localizer.getString('hpsum.common.server')+'</td></tr>');
                                            vparTable.append(vpar_hdr);

                                            for (var j = 0; j < device.VParArray.VPar.length; j++) {
                                                var vPar = device.VParArray.VPar[j];
                                                var vparRow = $('<tr></tr>').html('<td>' + vPar.Number + '</td><td>' + vPar.Name + '</td>');
                                                vparTable.append(vparRow);
                                            }

                                            vparDiv.append(vparTable);
                                            vparSection.append(vparDiv);
                                            details_cell.append(vparSection);
                                        }

                                        if (device.Blades.Blade.length > 0) {
                                            var bladeSection = $('<div></div>').addClass('hp-collapsible').html('<label>'+localizer.getString('hpsum.sd2oa.blades')+'</label>');
                                            var bladeDiv = $('<div></div>');
                                            var bladeTable = $('<table></table>');
                                            var blade_hdr = $('<thead></thead>');
                                            blade_hdr.append('<tr><td><div class=\"hp-status"></div></td><td>'+localizer.getString('hpsum.common.enclosure')+
                                            				'</td><td>'+localizer.getString('hpsum.sd2oa.bay')+'</td><td>'+localizer.getString('hpsum.common.model')+'</td><td>'+
                                            				localizer.getString('hpsum.sd2oa.cplxFW')+'</td><td>'+localizer.getString('hpsum.sd2oa.parFW')+'</td></tr>');
                                            bladeTable.append(blade_hdr);

                                            for (var j = 0; j < device.Blades.Blade.length; j++) {
                                                var blade = device.Blades.Blade[j];
                                                var complexFw, partitionFW;

                                                var hasMismatch = false;
                                                for (var k = 0; k < blade.FWVersionEx.length; k++) {
                                                    var fw = blade.FWVersionEx[k];

                                                    if (fw.FWVersionType == COMPLEX_FW) {
                                                        complexFw = fw.FWVersion;
                                                    } else if (fw.FWVersionType == PARTITION_FW) {
                                                        partitionFW = fw.FWVersion;
                                                    }

                                                    if (fw.FWMismatch == FW_MISMATCH) {
                                                        hasMismatch = true;
                                                    }
                                                }

                                                var bladeStatus = '';
                                                if (hasMismatch) {
                                                    bladeStatus = '<div title=\"Mismatch\" class=\"hp-status hp-status-warning\"></div>';
                                                } else {
                                                    bladeStatus = '<div class=\"hp-status hp-status-ok\"></div>';
                                                }

                                                var bladeRow = $('<tr></tr>').html('<td>' + bladeStatus + '</td><td>' + blade.Enclosure + '</td><td>' + blade.Bay + '</td><td>' + blade.Name + '</td><td>' + complexFw + '</td><td>' + partitionFW + '</td>');
                                                bladeTable.append(bladeRow);
                                            }

                                            bladeDiv.append(bladeTable);
                                            bladeSection.append(bladeDiv);
                                            details_cell.append(bladeSection);
                                        }
                                    }

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

                                partitionDiv.append(device_table);
                                partitionSection.append(partitionDiv);
                            }

                            var ubSection;
                            if (item.unassigned_blade_list.length > 0) {

                                ubSection = $('<div></div>').addClass('hp-collapsible sd2-section-title').html('<label>Unassigned Blades</label>');
                                var ubDiv = $('<div></div>');
                                var ubTable = $('<table></table>');
                                var hdr = $('<thead></thead>');
                                hdr.append('<tr><td><div class=\"hp-status"></div></td><td>'+localizer.getString('hpsum.common.enclosure')+
                                            '</td><td>'+localizer.getString('hpsum.sd2oa.bay')+'</td><td>'+localizer.getString('hpsum.common.model')+'</td><td>'+
                                            localizer.getString('hpsum.sd2oa.cplxFW')+'</td><td>'+localizer.getString('hpsum.sd2oa.parFW')+'</td></tr>');
                                ubTable.append(hdr);

                                for (var i = 0; i < item.unassigned_blade_list.length; i++) {
                                    var device = item.unassigned_blade_list[i];
                                    var complexFw, partitionFW;

                                    var hasMismatch = false;
                                    for (var k = 0; k < device.FWVersionEx.length; k++) {
                                        var fw = device.FWVersionEx[k];

                                        if (fw.FWVersionType == COMPLEX_FW) {
                                            complexFw = fw.FWVersion;
                                        } else if (fw.FWVersionType == PARTITION_FW) {
                                            partitionFW = fw.FWVersion;
                                        }

                                        if (fw.FWMismatch == FW_MISMATCH) {
                                            hasMismatch = true;
                                        }
                                    }

                                    if (hasMismatch) {
                                        bladeStatus = '<div title=\"Mismatch\" class=\"hp-status hp-status-warning\"></div>';
                                    } else {
                                        bladeStatus = '<div class=\"hp-status hp-status-ok\"></div>';
                                    }

                                    var dev_row = $('<tr></tr>').html('<td>' + bladeStatus + '</td><td>' + device.Enclosure + '</td><td>' + device.Bay + '</td><td>' + device.Name + '</td><td>' + complexFw + '</td><td>' + partitionFW + '</td>');
                                    ubTable.append(dev_row);
                                }

                                ubDiv.append(ubTable);
                                ubSection.append(ubDiv);
                            }

                            $(DEVICES).html('');
                            if (item.npar_list.length > 0) {
                                $(DEVICES).append(partitionSection);
                            }
                            if (item.unassigned_blade_list.length > 0) {
                                $(DEVICES).append(ubSection);
                            }
                            $(DEVICES + ' .hp-collapsible').hpCollapsible();
                            $(DEVICES + ' .sd2-section-title').removeClass('hp-collapsed');
                        } else {
                            $(FIRMWARE_VERSION).text('');
                            $(CPLX_NAME).text('');
                            $(SERIAL_NO).text('');
                            $(DEVICES).html('');
                        }
						$('#hpsum-warning-messages').hpsumWarnings(item, false);

                        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-sd2-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 populateAssociatedTargets(item){
                    if(item.assoc_device_list === undefined) 
                        return;
                    if(item.assoc_device_list.length == 0) {
                        $(NO_ASSOC_DEVICES).show();
                        return;
                    } else {
                        $(NO_ASSOC_DEVICES).hide();
                    }

                    var tablecontents2 = "<table><tr> <td> <u>" + localizer.getString('hpsum.enclosure.deviceType') + "</u> </td> <td> <u>" + localizer.getString('hpsum.common.ipDns') + "</u> </td></tr>";
                    for(var i=0; i<item.assoc_device_list.length; i++) {
                        tablecontents2 += '<tr><td>' + item.assoc_device_list[i].Name + '</td><td>' + item.assoc_device_list[i].NetworkAddress + '</td></tr>';
                    }
                    tablecontents2 += "</table>";
                    $(ASSOC_DEVICES).html(tablecontents2); 
                }
                
                function getComplexMismatchDetails(item) {
                    var cplxMismatchDetails = "<table>";
                    cplxMismatchDetails += '<thead><tr><td>Device Type</td><td>Bay Number</td><td>Enclosure Number</td><td>FW Version</td><td>Mismatch</td></tr></thead>';
                    
                    for(var i=0; i<item.complex_mismatch_list.length; i++) {
                        var mismatch = item.complex_mismatch_list[i];
                        cplxMismatchDetails += '<tr><td>' + getDeviceTypeString(mismatch.DeviceType) + '</td><td>' + mismatch.Bay + '</td><td>' + mismatch.Enclosure + '</td><td>'
                                                + mismatch.Version + '</td><td>Firmware Mismatch</td></tr>';
                    }
                    cplxMismatchDetails += "</table>";
                    
                    return cplxMismatchDetails;
                }
                
                function getDeviceTypeString(deviceType) {
                    
                    var deviceStr;
                    
                    switch(deviceType) {
                        case DEVICE_USCOREBLADE:
                            deviceStr = "Blade";
                            break;
                        case DEVICE_USCOREINTERCONNECT_USCORETRAY:
                            deviceStr = "Interconnect Tray";
                            break;
                        case DEVICE_USCOREPOWER_USCORESUPPLY:
                            deviceStr = "Power Supply";
                            break;
                        case DEVICE_USCOREFAN:
                            deviceStr = "Fan";
                            break;
                        case DEVICE_USCOREOA:
                            deviceStr = "Onboard Administrator";
                            break;
                        case DEVICE_USCORELCD:
                            deviceStr = "LCD";
                            break;
                        case DEVICE_USCOREENCLOSURE:
                            deviceStr = "Enclosure";
                            break;
                        case DEVICE_USCOREINTERPOSER:
                            deviceStr = "Interposer";
                            break;
                        case DEVICE_USCOREDVD:
                            deviceStr = "DVD";
                            break;
                        case DEVICE_USCOREGPSM:
                            deviceStr = "Global Partition Services module (GPSM)";
                            break;
                        case DEVICE_USCOREXFM:
                            deviceStr = "Crossbar Fabric Module (XFM)";
                            break;
                        case DEVICE_USCOREXIOX:
                            deviceStr = "IO Expander (XIOX))";
                            break;
                        default:
                            deviceStr = "Unknown";
                            break;
                    }
                
                    return deviceStr;
                }

                function onItemError(error) {
                    $(ROOT).append(noItem);
                }

                function onAssociationsError(error) {
                    //console.log(error);
                }

                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();
                    $(DESCRIPTION).hpEllipsis();
                    this.resume();
                };
            }

            return new SD2ShowOverviewView();
        }());

    return SD2ShowOverviewView;
});
