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

define(['hpsum/presenter/node/NodePresenter',
    'hp/core/Notifications',
    'hp/core/UrlFragment',
    'hp/model/Session',
    'hp/core/Router',
    'text!hpPages/core/no_details.html',
    'hp/core/Localizer',
    'hp/view/AssociationAddView',
    'hpsum/presenter/baseline/BaselinePresenter',
    'hpsum/view/node/jquery.hpsumWarnings', 
    'hp/view/NotificationsView',
    'hp/view/DialogView',
    'hp/lib/jquery.hpStatus',
    'jquery',
    'hpsum/view/node/jquery.hpsumInstallables',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpCollapsible',
    'lib/jquery.selectBox',
    'hp/lib/jquery.hpGridPanels'],

function(presenter, notifications, urlFragment, session, router, noneHtml, localizer, AssociationAddView, BaselinePresenter, NotificationsView, DialogView) { "use strict";

    var NodeShowOverviewView = (function() {
      
        var VIEW = '#hpsum-nodes-show';
        var ROOT = '#hpsum-node-show-overview-multi';
        var ADD_BASELINES = '#baselines-add';
        var REBOOTOPTION = '#hpsum-reboot-option';
        var INVENTORY = '#hpsum-node-multi-inventory';
		var DEPLOY = '#hpsum-node-multi-deploy-btn';
        var APPLY = '#hpsum-node-multi-apply';
        var USERNAME = '#hpsum-node-credential-username';
        var PASSWORD = '#hpsum-node-credential-password';
      	var MULTI_DEPLOY_DIALOG = '#hpsum-node-multi-deploy', 
	    MULTI_DEPLOY_BTN = '#hpsum-node-mdeploy-deploy', 
	    MULTI_ANALYSIS_BTN = '#hpsum-node-mdeploy-analysis', 
	    MULTI_CANCEL_BTN = '#hpsum-node-mdeploy-cancel',
	    COMPONENT_DIALOG = '#hpsum-component-dialog', 
	    SPLASH_DIALOG = '#hpsum-splash-dialog', 
	    SPLASH_SPINNER = '#hpsum-splash-spinner', 
	    MDD_CONTENTS = '#hp-mdeploy-dialog-variable-contents';
        var currBaselines = [], allBaselines = [];
        var numberOfNodes;
		var failedDependencyFound = false;
        var nodeid = [];
        var FIRMWARECHKBOXCOMP ='.firmwarechkbox',
            SOFTWARECHKBOXCOMP ='.softwarechkbox',
            DOWNGRADECHKBOXCOMP = '.downgradechkbox',
            REWRITECHKBOXCOMP = '.rewritechkbox',
            DELAYSEC= '#hpsum-node-delay-seconds',
            DELAYMSG= '#hpsum-node-reboot-message',
            ACTIVATE_SELECTION = '#hpsum-activate-selection',
            NO_REBOOT_REQ = '#hpsum-node-no-reboot-required',
       		GENERATE = '#hpsum-node-multi-generate-report',
			FIRMWARECHECKBOX = '#hpsum-node-reports-firmware-multi',
			INSTALLABLECHECKBOX = '#hpsum-node-reports-installable-multi',
			FAILEDDEPCHECKBOX = '#hpsum-node-reports-faileddep-multi',
			INSTALLEDCHECKBOX = '#hpsum-node-reports-installed-multi',
			COMBINEDCHECKBOX = '#hpsum-node-reports-combined-multi',
			REPORTFORMATHTML = '#hpsum-node-reports-html-multi',
			REPORTFORMATXML = '#hpsum-node-reports-xml-multi',
			REPORTFORMATCSV = '#hpsum-node-reports-csv-multi',
			RUNBACKCHECKBOX = '#chkbox-runbackReport-multi',			
			RPT_SPLASH_DIALOG = '#hpsum-report-wait-dialog-multi',
			RPT_SPLASH_SPINNER = '#hpsum-report-spinner-multi',
			REPORTSDIALOG = '#hpsum-all-reports-dialog-multi',
			REPORTS_TABLE = '#hpsum-reports-table-multi',
			REBOOT_DELAY_SEC = '60';     
        
        /**
         * Constructor
         */
        function NodeShowOverviewView() {
            
            var noItem;
            var baselinesTable = null;
            var nodeTable = null;
            var inventoryInProgress = false;
            var nodeItem=null;
            var baselines='',
            hotfixes='',
            selectedNodes = null,
            assocBaseline='',
            newBaseline = null,	
            newHotFix  = null,
            mDeployDialogContents = '',
            changes = [],
            assocHotFix = '';
            var allBaselines = [], currBaselines = [];
            var updateInProgress = false;
            var  rebootoptions  = {
                reboot:'If Needed',
                delay : REBOOT_DELAY_SEC,
                message :'Reboot at user request after deploy '
                };
                
            var  forceoptions  = {
               firmware :true,
               software :true
               };
               
            var optiondetails = {
                hapi : {
                    reboot_options : {
                        action : 'No',
                        delay : REBOOT_DELAY_SEC,
                        message : 'Reboot at user request after deploy '
                        },
                        activate_sfw : false,
                        installation_option : {
                            firmware : false,
                            software : false,
                            downgrade : false,
                            rewrite : false
                        }
                    }
                };
                
            var reportNodes,
            timer = null,
            inProgressTimer = null,
            inProgressReportId = null,
            reportWaitDialog,
            deleteInfoDialog,
            deleteReportId;
            

			function onKeyDown(event) {
					var keyCode = (event.which ? event.which : event.keyCode);
					if (keyCode == 27) {
						notifications.show(localizer.getString("hpsum.node.runningReportInBackMulti") +
										   localizer.getString("hpsum.node.referForReportStatus"), 'ok');
						//clearInterval(timer);
						closesReportGenerationWait();
						//populateReportsTable();
						//$(GENERATE).attr("disabled", false);
						event.preventDefault();
					}
			}

			function showReportGenerationWait() {

					var reportButtons = {};

					reportButtons[localizer.getString('hpsum.node.runbackReport')] = function() {
						notifications.show(localizer.getString("hpsum.node.runningReportInBackMulti") +
										   localizer.getString("hpsum.node.referForReportStatus"), 'ok');
						//clearInterval(timer);
						closesReportGenerationWait();
						//populateReportsTable();
						//$(GENERATE).attr("disabled", false);
					};

					if (!reportWaitDialog) {
						reportWaitDialog = $(RPT_SPLASH_DIALOG);
						reportWaitDialog.dialog({
							modal : true,
							dialogClass : 'hp-simple-dialog',
							position : "center",
							draggable : false,
							resizable : false,
							buttons : reportButtons,
							width : 260,
							height : 180
						});
					}
					$(RPT_SPLASH_SPINNER).show();
					$(document).bind('keydown', onKeyDown);
					reportWaitDialog.dialog('open');
				}

				function closesReportGenerationWait() {
					$(RPT_SPLASH_SPINNER).hide();
					if (reportWaitDialog) {
						$(document).bind('keydown', onKeyDown);
					   reportWaitDialog.dialog('close');
					}
				}
				
				function initReportsTable() {
					
					var dummyReportsData = [];
					$(REPORTS_TABLE).dataTable({
							oLanguage : {
							    sEmptyTable: localizer.getString("hpsum.node.noReports"),
							    sSearch: localizer.getString('hpsum.common.search')
							},
							bPaginate : false,
							bFilter : true,
							bInfo : false,
							bAutoWidth : false,
							bRetrieve : true,
							bDestroy : true,
							aaData : dummyReportsData,
							aoColumns : [{
								mDataProp : 'time_stamp'
							},{
								mDataProp : 'firmware_type'
							},{
								mDataProp : 'deploy_preview_type'
							},{
								mDataProp : 'installed_type'
							},{
								mDataProp : 'dependency_type'
							},{
                                mDataProp : 'combined_report'
                            },{
								mDataProp : 'report_format'
							},/*{
								mDataProp : 'node_name'
							},*/{
								mDataProp : 'report_status'
							},{
								mDataProp : 'delete_report'
							}],
							aaSorting: [[ 0, "desc" ]],
							bScrollCollapse : true
					});
				}

				function populateReportsTable(isItemOnChange) {	
					var reports = [],
					    firmware_report,
					    deploy_preview_report,
					    installed_report,
					    dependency_report,
					    combined_report,
					    nodes = [];

					presenter.getAllReports({
						success : function(data) {
							reports = data.hapi.reports.report;
							var tableReports = [],
							    reportTypes = [],
							    reportStatus,
							    inProgress = false;
							    							    
							for (var idx = 0; idx < reports.length; ++idx) {
								    reportStatus = reports[idx].report_state;
								    
								if (reportStatus == "report_generation_completed") {
									reportStatus = localizer.getString("hpsum.node.completed");
								} else if (reportStatus == "in_progress" || reportStatus == "not_started" || reportStatus == "partially_generated") {
									reportStatus = localizer.getString("hpsum.node.inProgress");
									inProgress = true;
									if (isItemOnChange) {
										inProgressReportId = reports[idx].report_id;

										$(GENERATE).attr("disabled", true);
										inProgressTimer = setInterval(function() {
											presenter.getReportStatus(inProgressReportId, {
												success : function(data) {
													if (data.hapi.report_state.match(/in_progress|not_started|partially_generated/i)) {
													} else if (data.hapi.report_state.match(/report_generation_completed/i)) {

														clearInterval(inProgressTimer);

														$(GENERATE).attr("disabled", false);
														populateReportsTable(false);

													} else {

														clearInterval(inProgressTimer);

													}
												},
												error : function(errorInfo) {

													clearInterval(inProgressTimer);
												}
											});

										}, 3000);
									}
								} else {
									reportStatus = localizer.getString("hpsum.node.failed");
								}

								    
								    reportTypes = reports[idx].report_type;
								    firmware_report = deploy_preview_report = 	installed_report = dependency_report = combined_report = "";					    
								    for (var i=0; i < reportTypes.length; i++) {
								    	
								    	if (reportTypes[i] == "firmware_report") {
								    		reportTypes[i] = "Firmware";
								    		if (inProgress) {
												firmware_report = '<img src="/img/hp-sum/jstree/throbber.gif">';
											} else { 	
								    		    firmware_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '.rpt"' + 'class="company-a" target ="_blank">' + 
								    		                   '<img src="/img/hp-piano/status-ok.png" ></br>' +
								    		                   localizer.getString("hpsum.node.viewDetails") + '</a>';
								    		}
								    	}
								    	else if (reportTypes[i] == "deploy_preview_report") {
								    		reportTypes[i] = "deploy_preview";
								    		if (inProgress) {
												deploy_preview_report = '<img src="/img/hp-sum/jstree/throbber.gif">';
											} else { 
								    		    deploy_preview_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '.rpt"' + 'class="company-a" target ="_blank">' +
								    		                      '<img src="/img/hp-piano/status-ok.png" ></br>' +
								    		                      localizer.getString("hpsum.node.viewDetails") + '</a>';
								    		}
								    	}
								    	else if (reportTypes[i] == "installed_report") {
								    		reportTypes[i] = "Installed";
								    		if (inProgress) {
												installed_report = '<img src="/img/hp-sum/jstree/throbber.gif">';
											} else { 
								    		    installed_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '.rpt"' + 'class="company-a" target ="_blank">' +
								    		                    '<img src="/img/hp-piano/status-ok.png" ></br>' +
								    		                     localizer.getString("hpsum.node.viewDetails") + '</a>';
								    		}
								    	}
								    	else if (reportTypes[i] == "dependency_report") {
								    		reportTypes[i] = "FailedDependency";
								    		if (inProgress) {
												dependency_report = '<img src="/img/hp-sum/jstree/throbber.gif">';
											} else { 
								    		    dependency_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '.rpt"' + 'class="company-a" target ="_blank">' +
								    		                     '<img src="/img/hp-piano/status-ok.png" ></br>' +
								    		                   localizer.getString("hpsum.node.viewDetails") + '</a>';
								    		}
								    	}
								    	else if (reportTypes[i] == "combined_report") {
                                            reportTypes[i] = "Combined";
                                            if (inProgress) {
                                                combined_report = '<img src="/img/hp-sum/jstree/throbber.gif">';
                                            } else { 
                                                combined_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '.rpt"' + 'class="company-a" target ="_blank">' +
                                                                 '<img src="/img/hp-piano/status-ok.png" ></br>' +
                                                               localizer.getString("hpsum.node.viewDetails") + '</a>';
                                            }
                                        }
								    }
								
								inProgress = false;
								
								var deleteReport = '<a id="hpsum-delete-report" data-custom-value="' + reports[idx].report_id + '">' +
								'<img src="/img/hp-piano/close.png" >' + '</a>';
								
								tableReports.push({
									time_stamp : reports[idx].date_and_time,
									report_format : reports[idx].report_format,
									firmware_type : firmware_report,
									deploy_preview_type : deploy_preview_report,
									installed_type : installed_report,
									combined_report: combined_report,
									dependency_type : dependency_report,
									report_status : reportStatus,
									node_name : reports[idx].node_id,
									delete_report : deleteReport
								});
							}
							
							initReportsTable();
	
							presenter.getAllNodes({
								success : function(data) {
									nodes = data.hapi.output_data.nodes.node;

									for (var jdx = 0; jdx < tableReports.length; ++jdx) {
										for (var idx = 0; idx < nodes.length; ++idx) {
											if (nodes[idx].node_id == tableReports[jdx].node_name) {
												tableReports[jdx].node_name = nodes[idx].node_name;
												break;
											}
										}
									}

									$(REPORTS_TABLE).dataTable().fnClearTable();
									$(REPORTS_TABLE).dataTable().fnAddData(tableReports);

								},
								error : function() {
								}
							}); 

									    
							$(REPORTS_TABLE).dataTable().fnClearTable();
							$(REPORTS_TABLE).dataTable().fnAddData(tableReports);
						},
						error : function(errorMsg) {
							notifications.show(errorMsg, 'error');
							$(GENERATE).attr("disabled", false);
						}
					});
				};
				
				function onGenerate() {

					$(GENERATE).attr("disabled", true);

					if (!$(RUNBACKCHECKBOX).is(':checked')) {
						showReportGenerationWait();
					}
					
					var request,
					    firmwaretype = "false",
					    deploy_previewtype = "false",
					    faileddeptype = "false",
					    installedtype = "false",
					    combinedtype ="false",
					    reportformat = "false";

					if ($(REPORTFORMATHTML).is(':checked')) {
						reportformat = $(REPORTFORMATHTML).val();
					} else if ($(REPORTFORMATXML).is(':checked')) {
						reportformat = $(REPORTFORMATXML).val();
					} else if ($(REPORTFORMATCSV).is(':checked')) {
						reportformat = $(REPORTFORMATCSV).val();
					}

					if ($(FIRMWARECHECKBOX).is(':checked')) {
						firmwaretype = "true";
					}
					if ($(INSTALLABLECHECKBOX).is(':checked')) {
						deploy_previewtype = "true";
					}
					if ($(FAILEDDEPCHECKBOX).is(':checked')) {
						faileddeptype = "true";
					}
					if ($(INSTALLEDCHECKBOX).is(':checked')) {
						installedtype = "true";
					}
					if ($(COMBINEDCHECKBOX).is(':checked')) {
                        combinedtype = "true";
                    }
					
					var requestNodeArray = [];
					for (var i=0; i<reportNodes.count; i++){
						requestNodeArray.push({
									node_id : reportNodes.node_id[i],
									firmware_report : firmwaretype,
									deploy_preview_report : deploy_previewtype,
									dependency_report : faileddeptype,
									installed_report : installedtype,
									combined_report : combinedtype
						});
					}
                    
					var request = {
						hapi : {
							report_format : reportformat,
							baseline_report: "false",
							nodes : {
								node : requestNodeArray
							}
						}
					};

					presenter.createReport(request, {
						success : function(data) {
							onSuccessReportCreation(data.hapi.report_id);
						},
						error : function(errorInfo) {
							notifications.show(errorInfo, 'error');
							closesReportGenerationWait();
							$(GENERATE).attr("disabled", false);
						}
					});

				}

				function getReportStatus(reportId) {
					//var status = "";
					timer = setInterval(function() {
						presenter.getReportStatus(reportId, {
							success : function(data) {
							 // if (status != data.hapi.status) {
								//status = data.hapi.status;
								if (data.hapi.report_state.match(/in_progress|not_started|partially_generated/i)) {
								} else if (data.hapi.report_state.match(/report_generation_completed/i)) {
									notifications.show(localizer.getString("hpsum.node.doneReportMulti") +
													   localizer.getString("hpsum.node.referForReportStatus"), 'ok');
									closesReportGenerationWait();
									clearInterval(timer);
									$(GENERATE).attr("disabled", false);
									populateReportsTable(false);
								} 
								//else if (data.hapi.status.match(/partially_generated/i)) {
									//notifications.show(localizer.getString("hpsum.node.partialReportMulti") +
										//			   localizer.getString("hpsum.node.referForReportStatus"), 'warning');
									//closesReportGenerationWait();
									//clearInterval(timer);
									//$(GENERATE).attr("disabled", false);
									//populateReportsTable();
									//}
								 else {
									notifications.show(localizer.getString("hpsum.node.failedReportMulti"), 'error');
									closesReportGenerationWait();
									clearInterval(timer);
									$(GENERATE).attr("disabled", false);
								}
							// }
							},
							error : function(errorInfo) {
								notifications.show(errorInfo, 'error');
								closesReportGenerationWait();
								clearInterval(timer);
								$(GENERATE).attr("disabled", false);
							}
						});

					}, 3000);
				}

				function onSuccessReportCreation(reportId) {
					//$(GENERATE).attr("disabled", false);
					populateReportsTable(false);
					presenter.generateReport(reportId, {
						success : function(data) {
							if (!$(RUNBACKCHECKBOX).is(':checked')) {
								getReportStatus(reportId);
							} else {
								notifications.show(localizer.getString("hpsum.node.runningReportInBackMulti") +
												   localizer.getString("hpsum.node.referForReportStatus"), 'ok');
							    populateReportsTable(false);
								//$(GENERATE).attr("disabled", false);
								getReportStatus(reportId);
							}
						},
						error : function(errorInfo) {
							notifications.show(errorInfo, 'error');
							closesReportGenerationWait();
							$(GENERATE).attr("disabled", false);
							populateReportsTable(false);
						}
					});
				}
				
				function onDeleteReport() {
					var deleteConfirmButtons = {};

					deleteConfirmButtons[localizer.getString('hpsum.baseline.show.yesDelete')] = function() {
						presenter.deleteReport({report_id : deleteReportId},
							{
							success : function(data) {
								notifications.show(data.hapi.hmessage, 'ok');
								populateReportsTable(false);
							},
							error : function(message) {
								notifications.show(message, 'error');
							}
						});
						deleteInfoDialog.dialog('close');
					};

					deleteConfirmButtons[localizer.getString('hpsum.common.button.cancel')] = function () {
						deleteInfoDialog.dialog('close');
					};
					
					if (!deleteInfoDialog) {
						deleteInfoDialog = $('#hpsum-delete-report-dialog');
						deleteInfoDialog.dialog({
							modal : true,
							dialogClass : 'hp-simple-dialog',
							position : "center",
							draggable : false,
							resizable : false,
							buttons : deleteConfirmButtons
						});
					}
					
					deleteInfoDialog.dialog('open');	
				}

            function onChange() {   
                    var baseline = [];                     
                   var i;
                            for (i=0; i<currBaselines.length; i++ ){
                            baseline[i] = presenter.getBaselineDetailsforName(currBaselines[i].baseline);
                            if(baseline[i])
                                assocBaseline = baseline[i];
                                }
                     }
              

            function initNodeTable(){
                $("#hpsum-node-table > tbody > tr").remove();
                $("#hpsum-node-table_filter").remove();
                $("#hpsum-node-table_processing").remove();
                
                nodeTable = $('#hpsum-node-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: 'node'},
                            {mDataProp: 'type'},
                            {mDataProp: 'state'},
                            {mDataProp: 'status'},
                            {mDataProp: 'phase'},
							{mDataProp: 'comments'}
                            ],
                    aaSorting: [[ 0, "asc" ]],
                    });

            }

            function onAggregateChange(aggregate) {
            	if (timer) {
						clearInterval(timer);
						timer = null;
				}
                $(ROOT).removeClass('hp-show-changing');
                $(ADD_BASELINES).removeAttr("disabled");
                $('.hp-dynamic', ROOT).removeClass('hp-unavailable');
                $.each(['error', 'warning', 'ok', 'unknown', 'disabled'], function (index, status) {
                });
                $('.hp-grid-panels').hpGridPanels();
               
                numberOfNodes = aggregate.count;   
                reportNodes = aggregate;
                selectedNodes = aggregate;
                
                initNodeTable();
                nodeTable.fnClearTable();
            
                var i;
				$(DEPLOY).attr("disabled", false);
				$(INVENTORY).attr("disabled", false);
                for (i=0; i<aggregate.count; i++){
				if (aggregate.node_state[i] != "UAN") {
					$(DEPLOY).attr("disabled", true);
				}
				if(aggregate.node_phase[i] == "Scheduled" &&
					aggregate.node_state[i] == "SCHEDULED")
					$(INVENTORY).attr("disabled", true);
					
				if (aggregate.node_phase[i] == "UnKnown" && 
				   (aggregate.node_state[i] != "UAN" || 
				    aggregate.node_state[i] != "IDLE" ||
					aggregate.node_state[i] != "INSTALLDONE")) {
				$(INVENTORY).attr("disabled", true);	
				}
                    var tableItem = [{
                                    node:aggregate.node_name[i],
                                    type:aggregate.node_type[i],
                                    state:aggregate.node_state[i],
                                    status:aggregate.node_status[i],
                                    phase:aggregate.node_phase[i],
									comments:''
                                }];
					if(aggregate.node_state[i] === "SCHEDULED") {
						tableItem[0].status = "Scheduled";
						tableItem[0].comments = "Selection of a scheduled node prevents \"Inventory\" and \"Deploy\" actions on multiple nodes, please deselect to enable.";
					}
                   if(aggregate.node_name[i] === undefined || aggregate.node_name[i] === null) {
	                    //Invalid data, go back to node overview
	                    router.go('/node/show/' + aggregate.node_type[0].toLowerCase() + '/overview/r/Session/' + session.getToken() + '/Node/'+ aggregate.node_id[0] + '/getdata');
	                } else 
	                    nodeTable.fnAddData(tableItem);
	                
	                nodeid [i] = aggregate.node_id[i];
	               	
					
					var analysisInProgress = false;
					for (var j = 0; j < numberOfNodes; j++) {
						if (changes[j] === undefined || changes[j] === null) {
							break;
						}
						
						if ((changes[j].node_id == aggregate.node_id[i]) && (changes[j].current_state === "ANALYSIS")) {
							analysisInProgress = true;
							break;
						}
					 }

		       		if (analysisInProgress) {
		       			continue;
		       		}
		       		
					changes[i] = {
								node_id : nodeid[i],
								changed : false,
								init : false,
								current_state : aggregate.node_state[i]
							};

            	}

				initActionBaselineTable();
                var baselinesTable = $('#baselines_table').dataTable();
                baselinesTable.fnClearTable();

               	$('#baselines_table' + ' .hp-close').click(onDeleteBaseline);
           	}

            
            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');
                }
            }
          
            function initActionBaselineTable() {
                
                //Initialize baselines table in the action dialog

                 baselinesTable = $('#baselines_table').dataTable({
                    oLanguage: {
                        sEmptyTable: localizer.getString('hpsum.node.noItemsFound'),
                        sSearch: localizer.getString('hpsum.common.search')
                               },
                    bPaginate : false,
                    bProcessing : true,
                    bFilter : true,
                    bSort : false,
                    bAutoWidth : false,
                    bInfo : false,
                    bRetrieve : true,
                    bDestroy : true,
                    aaData: currBaselines,
                    aaSorting: [[ 0, "asc" ]],
                    aoColumns : [
                        {mDataProp: 'baseline', sDefaultContent:''},
                        {mDataProp: 'descr', sDefaultContent:''},
                        {mDataProp: 'uri', "bVisible": false},
                        {fnRender: function (oObj) {
                           return '<div class="hp-close"></div>';
                        }, sClass: 'hp-icon', sWidth: 20, mDataProp: '',sDefaultContent:''}
                    ]
                });
                  $('#baselines_table' + ' .hp-close').click(onDeleteBaseline);
            }


            function onAddBaselines() {
                loadBaselines();
                var numAdded = 0;
                new AssociationAddView({
                    title: localizer.getString("hpsum.oneTouchUpdate.addBaselines"),
                    dataTableOptions:  {
                        aoColumns : [
                          {sTitle: localizer.getString("hpsum.common.baseline"), mDataProp: 'baseline', sWidth: 100, sDefaultContent: ''},
                          {sTitle: localizer.getString("hpsum.common.locationStr"), mDataProp: 'descr', sWidth: 200, sDefaultContent: ''},
                          {mDataProp: 'uri', bVisible: false}
                        ],
						oLanguage: {
						    sEmptyTable: localizer.getString("hpsum.baseline.show.allBaselinesSelected"),
						    sSearch: localizer.getString('hpsum.common.search')
							   }
                    },
                    getResults: function (query, handlers) {
                        // simulate error if string is "error"
                        if ('error' === query) {
                            handlers.error(localizer.getString("hpsum.oneTouchUpdate.addBaselinesError"));
                        } else {
                            // It is assumed this would be performed on the server side
                            handlers.success(getBaselineAssociations(query));
                        }
                    },
                    apply: function (results) {
                        numAdded += results.length;
                        currBaselines = currBaselines.concat(results);
                        baselinesTable.fnAddData(results);
                        baselinesTable.fnAdjustColumnSizing();
                        $('#baselines_table' + ' .hp-close').
                            click(onDeleteBaseline);
                            
                        if (currBaselines.length || allBaselines.length === 0)
                            $(ADD_BASELINES).attr("disabled","disabled");
                        else
                            $(ADD_BASELINES).removeAttr("disabled");
                    }
                });
            }


        function getBaselineSuccess(baselines) {
                
                allBaselines = [];
                currBaselines = [];
            
                initActionBaselineTable(); 

                for(var i=0; i < baselines.length; i++)
                {
                    allBaselines.push({
                        baseline: baselines[i].baseline_name,
                        descr: baselines[i].baseline_url,
                        uri: baselines[i].baseline_uri
                    });
                    
                }

                if (currBaselines.length || allBaselines.length === 0)
                    $(ADD_BASELINES).attr("disabled","disabled");
                else
                    $(ADD_BASELINES).removeAttr("disabled");
            }
            
            function getBaselineError(error) {
                
            }
            
            function loadBaselines() {
                
                var handlers =  {
                                success : function(data) {
                                    getBaselineSuccess(data);
                                },
                                error : function(errorInfo) {
                                    getBaselineError(errorInfo);
                                }
                            }
                
                BaselinePresenter.getBaselines(handlers);
            }

             function onDeleteBaseline(event) {
                var row = $(this).parents('tr')[0];
                var association = baselinesTable.fnGetData(row);
                $('#hpsum-inventory-error').text("");
                
                if(association === null)
                    return;
                    
                currBaselines = $.grep(currBaselines, function (association2) {
                    return association2.uri !== association.uri;
                });
                baselinesTable.fnDeleteRow(row);
                event.stopPropagation();
                
                if (currBaselines.length)
                    $(ADD_BASELINES).attr("disabled","disabled");
                else
                    $(ADD_BASELINES).removeAttr("disabled"); 
            }

            function getBaselineAssociations(search) {
                var regexp = new RegExp(search, 'i');
                var results =
                    $.grep(allBaselines, function(result, index) {
                        // exclude existing
                        if ($.grep(currBaselines, function(result2, index2) {
                            return (result2.uri === result.uri);
                        }).length > 0) {
                            return false;
                        }
                        // check search
                        if (search && search.length > 0) {
                            return (result.baseline.match(regexp) ||
                                    result.descr.match(regexp));
                        }
                        return true;
                    });
                return ({count: results.length, members: results});
            }

               function onInventoryError(errorMessage) {
                   inventoryInProgress = false;
                   $('#hpsum-inventory-error').text(errorMessage);
            }

            function onInventorySuccess(item) {
                inventoryInProgress = false;
            }

            
            function onInventory() {
                var fail=false;
                var finalBaseline;
                var finalHotFix;
                var baselineJson=[];
                $('#hpsum-inventory-error').text("");
                //showInventoryProgress(); 
                onChange();
                if (! inventoryInProgress) {
                    if((newBaseline == null) && (assocBaseline == null))
                        finalBasline = null;
                    else if (newBaseline == null)
                        finalBaseline = currBaselines;
                    else
                        finalBaseline = newBaseline;
                    if((newHotFix == null) && (assocHotFix == null))
                        finalHotFix = null;
                    else if (newHotFix == null)
                        finalHotFix = assocHotFix;
                    else
                        finalHotFix = newHotFix;
                        
                    if((finalHotFix == null) &&  (finalBaseline == null))
                        fail = true;
                    else if(finalHotFix == null)
                        baselineJson.push(finalBaseline.id);
                    else if (finalBaseline == null)
                        baselineJson.push(finalHotFix.id);
                    else{
                        if(finalBaseline)
                            baselineJson.push(finalBaseline.id);
                        if(finalHotFix)
                            baselineJson.push(finalHotFix.id);
                    }
                    if(fail == true){
                        $(FAILEDPANEL).show();
                        $(FAILEDMSG).text(localizer.getString('hpsum.node.errorPleaseSelectBaseline'));
                    }
                    else {
                    inventoryInProgress = true;
                    for(var i=0;i<numberOfNodes;i++) {
                    presenter.startInventorymulti(nodeid[i],assocBaseline,{
                        success : onInventorySuccess,
                        error : onInventoryError
                    });
            }
                   }
                }
                
                $(USERNAME).val("");
                $(PASSWORD).val("");
            }

            function onApply() {

                if ( ! ($(USERNAME).val() === '' || $(PASSWORD).val() === '')) {
                    updateInProgress = true;
                    var editOptions =  {
                        hapi: {
                        username : $(USERNAME).val(),
                        password : $(PASSWORD).val()
                        }
                    };
                    for(var i=0;i<numberOfNodes;i++) {
                    presenter.setattributemulti(nodeid[i], editOptions, {
                        success : onItemUpdateSuccess,
                        error : onItemUpdateError
                    });
                }
                $(USERNAME).val("");
                $(PASSWORD).val("");
                }
            }
            
            function onItemUpdateError(errorMessage) {
                updateInProgress = false;
            }

            function onItemUpdateSuccess(item) {
                updateInProgress = false;
            }
            
            function onsetoptiondetails(){
                
                optiondetails.hapi.installation_option ={};
                optiondetails.hapi.installation_option.downgrade = $(DOWNGRADECHKBOXCOMP).is(':checked'); 
                optiondetails.hapi.installation_option.rewrite = $(REWRITECHKBOXCOMP).is(':checked');
                optiondetails.hapi.installation_option.software =  $(SOFTWARECHKBOXCOMP).is(':checked');  
                optiondetails.hapi.installation_option.firmware =  $(FIRMWARECHKBOXCOMP).is(':checked');

                optiondetails.hapi.reboot_options.action = $(REBOOTOPTION).val();
                optiondetails.hapi.reboot_options.delay = $(DELAYSEC).val();                
                optiondetails.hapi.reboot_options.message = $(DELAYMSG).val();
                
                var tmp = $(ACTIVATE_SELECTION).val();
                if( tmp == 'NO') {
                    optiondetails.hapi.activate_sfw = false;
                } else {
                    optiondetails.hapi.activate_sfw = true;
                }
                
                var baselinesTable = $('#baselines_table').dataTable();
                if(baselinesTable) {
                	var baselinesSelected = [];
                	var baselinesData = baselinesTable.fnGetData();
                	for(var i=0; i < baselinesData.length; i++)
                	{
                		var uri = baselinesData[i].uri;
                		var paths = uri.split("/");
	            		var baseline_id = paths[5] + "/" + paths[7];
                		baselinesSelected.push(baseline_id);
                	}
                	
                	if(baselinesSelected.length > 0)
                	{
                		optiondetails.hapi.baselines = {remove_existing_baselines:'true'};
                        optiondetails.hapi.baselines.baseline = baselinesSelected;
                	}
                }

                for(var i=0;i<numberOfNodes;i++) {
                    presenter.setattributemulti(nodeid[i], optiondetails, {
                        success : onsetattributeSuccess,
                        error : onsetattributeerror
                    });
                }
                
            }
            /**
             * @private
             * Call presenter's onAnalysis() to check for dependencies for a selected component/baseline to the node 
             */
                
                    
            function onsetattributeSuccess(item) {               
               //do nothing
            }
            
            function onsetattributeerror(errorMessage) {       

            }

             function showInventoryProgress(){
                   var  inventoryTimer = setInterval(function () {
                    
                    var i;
                    for ( i=0; i< numberOfNodes; i++)
                    {
                    presenter.getNodeStatusmulti(nodeid[i], {
                                success : function(data) {
                                    onNodeStatusSuccess(data, inventoryTimer);
                                },
                                error : function(errorInfo) {
                                    onNodeStatusError(errorInfo, inventoryTimer);
                                }
                            });
                }
                            
                }, 3000);
            }
            
            function onNodeStatusSuccess(data, inventoryTimer){
            }
            
            function onNodeStatusError(error, inventoryTimer){
                
            }
				function showApplicableComponents(ev) {
					var nodeItem = {
						node_id : ev.data.value,
						node_type: ''
					};
					var command = 'init';
					for (var i = 0; i < numberOfNodes; i++) {
						if(changes[i].node_id == nodeItem.node_id) {
							nodeItem.type = selectedNodes.node_type[i];
							if((changes[i].changed == true) && (changes[i].init == false))
								command = 'recalculate';
							else {
								if(changes[i].init == true) 
									return;
								else {
									changes[i].init = true; //first time and after analysis is done.
								}
							}
						}
					}
					var cContentId = '#hpsum-md-ccontent-' + ev.data.value;
					$(cContentId, mDeployDialogContents).html("<label>" + localizer.getString("hpsum.common.loading") + "<label>");
					
					if(command == 'init') {	
					var options = { command: command,
									nodeItem:nodeItem,
									onSelectionChanged:onSelectionChanged};
					$(cContentId,mDeployDialogContents).hpsumInstallables(options);
					}
					else
						$(cContentId,mDeployDialogContents).hpsumInstallables(command);
				}
				function onSelectionChanged(id, value, componentList){
					if(value == true){
						$(MULTI_ANALYSIS_BTN).attr("disabled", false);
						$(MULTI_DEPLOY_BTN).attr("disabled", true);
					}
					else{
						//$(MULTI_ANALYSIS_BTN).attr("disabled", true);
						var deployflag = 'true';
						var val = $(MULTI_ANALYSIS_BTN).prop("disabled");
						if($(MULTI_ANALYSIS_BTN).prop("disabled")){
							if((componentList.component.length > 0)&& (componentList.failed_dependency == 0)){
								for (var i = 0; i < numberOfNodes; i++) {
									if(id  == selectedNodes.node_id[i])
										continue;
									var id = '#hpsum-md-cname-' + selectedNodes.node_id[i];
									if($(id)[0].innerHTML.match(/failed/i))
										deployflag = false;
								}
								if(deployflag && !failedDependencyFound)
									$(MULTI_DEPLOY_BTN).attr("disabled", false);
							}
							else if(componentList.failed_dependency > 0){
								$(MULTI_DEPLOY_BTN).attr("disabled", true);
								failedDependencyFound = true;
							}
						}
					}
					var nodeName='';
					for (var i = 0; i < numberOfNodes; i++) {
						if (changes[i].node_id == id){
							changes[i].changed = value;
							nodeName= selectedNodes.node_name[i];
						}
					}
					var name  = '#hpsum-md-cname-' + id;
					if(componentList.failed_dependency != 0){
						$(name).html('<img src="/img/hp-piano/status-error.png">' +nodeName + '<br/>' + localizer.getString("hpsum.node.compFailedDep") );
						$(name).css("vertical-align","middle");
					}
					else{
						if(componentList.component.length == 0){
							$(name).html('<img src="/img/hp-piano/status-ok-unset.png" >' + nodeName + '<br/>' + localizer.getString("hpsum.node.compSelectZero") );
							$(name).css("vertical-align","middle");
						}
						else{
							$(name).html('<img src="/img/hp-piano/status-ok.png">' +nodeName + '<br/>'+ localizer.getString("hpsum.node.compSelect", [ componentList.component.length ]));
							$(name).css("vertical-align","middle");
							}	
					}
				}

				function onPopulateError(id) {
				    $(id).html('<label>' + localizer.getString("hpsum.common.loading") + '</label>');
				}

				            

				function onMultiAnalyze() {
					showAnalysisSplash();
					var changedNodes = 0;
					for (var i = 0; i < numberOfNodes; i++) {
						if (changes[i].changed == true) {
							changes[i].current_state= "ANALYSIS";
							//var tableid = '#hpsum-otu-installables-' + changes[i].node_id + '-table';
							var cContentId = '#hpsum-md-ccontent-' + changes[i].node_id;
							var options = {command:'getComponents'};
							//var installables = $(cContentId,mDeployDialogContents).hpsumInstallables(options);
							var inst = $(cContentId).data('plugin_hpsumInstallables');
							var componentsList = inst.getComponents();
							
							var nodeItem = {
								node_id : changes[i].node_id
							};
							changedNodes++;
							presenter.analysis(nodeItem, componentsList, {
								node_id : nodeItem.node_id,
								success : function(data) {
									//analyzeSuccess(data, this.node_id);
								},
								error : function(errorInfo) {
									changes[i].changed = true;
									analyzeError(errorInfo, node_id);
									changedNodes--;
								}
							});
						}
					}
					//Now send getstatus to all the changed nodes and wait till all moves to UAN.
					var finishedAnalysis = 0;
					var splashClosed = false;
					var progressTimer = setInterval(function() {
						for (var i = 0; i < numberOfNodes; i++) {
							if (changes[i].changed == true) {
								var nodeItem = {
									node_id : changes[i].node_id
								};
								presenter.getNodeStatus(nodeItem, {
									success : function(data) {
										if (data.hapi.node_status.node_state === "UAN") {
                                            for (var j = 0; j < numberOfNodes; j++) {
                                                if(changes[j].node_id == data.hapi.node_status.node_id ) {
                                                    if(changes[j].current_state === "ANALYSIS"){
                                                    finishedAnalysis++;
                                                    changes[j].current_state = "UAN";                     
                                                    }                           
                                                }                               
									        }
                                        }else if (data.hapi.node_status.node_state === "ERROR") {
										    for (var j = 0; j < numberOfNodes; j++) {
                                                if(changes[j].node_id == data.hapi.node_status.node_id ) {
                                                   if(changes[j].current_state === "ANALYSIS"){
                                                   finishedAnalysis++;
                                                   changes[j].current_state = "ERROR";    
											       changes[j].changed = true;
											       analyzeError(errorInfo, node_id);
										           }
											    }
										    }
										} 
									},
									error : function() {

									}
								});

							}
							
							if (finishedAnalysis >= changedNodes) {
								clearInterval(progressTimer);
								//Now open all collapsibles for all nodes that have been changed. That wil
								//internally call getupdatelist for all those
								failedDependencyFound = false;
								for (var j = 0; j < numberOfNodes; j++) {
									var collapsibleId = '#hpsum-md-collapse-' + changes[j].node_id;
									$(collapsibleId, mDeployDialogContents).hpCollapsible('collapse');
									$(collapsibleId, mDeployDialogContents).hpCollapsible('expand');
									if (changes[j].changed == true) {
										//changes[j].changed = false;
										changes[j].init = false;
										}else  {
										var collapsibleId = '#hpsum-md-collapse-' + changes[j].node_id;
											$(collapsibleId, mDeployDialogContents).hpCollapsible('collapse');
										
									}
								}
								if(!splashClosed){
									closeAnalysisSplash();
									splashClosed = true;
								}
								$(MULTI_ANALYSIS_BTN).attr("disabled", true);
								$(MULTI_DEPLOY_BTN).attr("disabled", true);
							}
						}
					}, 3000);

				}

				function analyzeError(error, node_id) {
					var cContentId = 'hpsum-md-ccontent-' + node_id;
					cContentId.html('<label>' + localizer.getString("hpsum.node.failedAnalysis") + '</label>');
					var collapsibleId = '#hpsum-md-collapse-' + node_id;
					$(collapsibleId, mDeployDialogContents).hpCollapsible('collapse');
					$(collapsibleId, mDeployDialogContents).hpCollapsible('expand');

				}

				function showAnalysisSplash() {

					$(SPLASH_DIALOG).dialog({
						modal : true,
						position : "center",
						draggable : false,
						resizable : false,
						show : 'fade',
						dialogClass : 'hp-splash-dialog',
						width : 400
					});

					$(SPLASH_SPINNER).show();
				}

				function closeAnalysisSplash() {
					$(SPLASH_SPINNER).hide();
					$(SPLASH_DIALOG).dialog('destroy');
				}

				function onDeploy() {
					var htmlContents = '';
					for (var i = 0; i < numberOfNodes; i++) {
						var id = 'hpsum-md-collapse-' + selectedNodes.node_id[i];
						var contentid = 'hpsum-md-ccontent-' + selectedNodes.node_id[i];
						var name  = 'hpsum-md-cname-' + selectedNodes.node_id[i];
						htmlContents += '<div class ="my-collapsible" id ="' + id + '" data="' + selectedNodes.node_id[i] + '"><label id ="'+ name +'" >' + selectedNodes.node_name[i] + '</label>' + '<div id ="' + contentid + '"><label>Collapse Content</label></div></div>';
					}

					$(MDD_CONTENTS, mDeployDialogContents).html(htmlContents);
					
					$('.my-collapsible', mDeployDialogContents).hpCollapsible();
					for (var i = 0; i < numberOfNodes; i++) {
						var idC = '#hpsum-md-collapse-' + selectedNodes.node_id[i];
						$(idC, mDeployDialogContents).on('expand', {
							value : selectedNodes.node_id[i]
						}, function(ev) {
							showApplicableComponents(ev);
						});
						$(idC, mDeployDialogContents).hpCollapsible('expand');
						if (i != 0)
							$(idC, mDeployDialogContents).hpCollapsible('collapse');
					}
					
					
					$(MULTI_ANALYSIS_BTN, mDeployDialogContents).on('click', onMultiAnalyze);
					var deployStarted = 0;
					var dialogView = new DialogView();
					dialogView.init({
						contents : mDeployDialogContents,
						position : "center",
						ok : function(elem) {
							for (var i = 0; i < numberOfNodes; i++) {
								if (selectedNodes.node_state[i] == 'UAN' && selectedNodes.node_type[i] === 'OA') {
									deployStarted++;
									var nodeItem = {
										node_id : selectedNodes.node_id[i]
									};
				
									{
										presenter.deploy(nodeItem, {
											success : function(){
												deployStarted--;
												if (deployStarted == 0)
													$(MULTI_CANCEL_BTN, mDeployDialogContents).trigger('click');
											},
											error : function() {
												deployStarted--;
												if (deployStarted == 0)
													$(MULTI_CANCEL_BTN, mDeployDialogContents).trigger('click');
											}
										});
										  
									}
								}
							}
							for (var i = 0; i < numberOfNodes; i++) {
								if (selectedNodes.node_state[i] == 'UAN' && selectedNodes.node_type[i] !== 'OA') {
									deployStarted++;
									var nodeItem = {
										node_id : selectedNodes.node_id[i]
									};
				
									{
										presenter.deploy(nodeItem, {
											success : function(){
												deployStarted--;
												if (deployStarted == 0)
													$(MULTI_CANCEL_BTN, mDeployDialogContents).trigger('click');
											},
											error : function() {
												deployStarted--;
												if (deployStarted == 0)
													$(MULTI_CANCEL_BTN, mDeployDialogContents).trigger('click');
											}
										});
										  
									}
								}
							}
						},
						cancel : function() {
							$('.hpsumInstallables').hpsumInstallables('destroy');
							$(MULTI_ANALYSIS_BTN, mDeployDialogContents).off('click', onMultiAnalyze);
							for (var i = 0; i < numberOfNodes; i++) {
								changes[i].changed = false;
								changes[i].init = false;
							}
						}
					});
				}

                //Set the View filter for deployment type
                function setViewFilter() {
                    var loc = router.location();
                    if (loc.match(/ilo/i)) {
                        if (loc.match(/ilo_federation/i))
                            presenter.setFilter("type:ilo_federation");
                        else
                            presenter.setFilter("type:ilos");
                    } else if (loc.match(/vc/i))
                        presenter.setFilter("type:virtual_connect");
                    else if (loc.match(/enclosure/i))
                        presenter.setFilter("type:enclosures");
                    else if (loc.match(/ipdu/i))
                        presenter.setFilter("type:ipdu");
                    else if (loc.match(/moonshot/i))
                        presenter.setFilter("type:moonshot");
                    else if (loc.match(/server/i))
                        presenter.setFilter("type:servers");
                    else if (loc.match(/switch/i))
                        presenter.setFilter("type:switches");
                    else if (loc.match(/vmware/i))
                        presenter.setFilter("type:vmware");
                }

            /**
            /**
             * @public
             */
            this.resume = function() {
            	if (timer) {
						clearInterval(timer);
						timer = null;
				}
				if (inProgressTimer) {
						clearInterval(inProgressTimer);
						inProgressTimer = null;
				}
	
                if(router.location().indexOf("/node") != 0) {
                    //If deployment type menu selected
                    setViewFilter();
                }
                
                $('#hpsum-node-actions').hide();
                $('#hpsum-nodes-panel-selector').hide();
                $('#hpsum-user-error').hide();
                $('#hpsum-password-error').hide();
                $('#hpsum-inventory-error').text("");
                $(USERNAME).val("");
                $(PASSWORD).val("");
                $(ADD_BASELINES).removeAttr("disabled");
                presenter.on("selectionChange", onSelectionChange);
                presenter.on("aggregateChange", onAggregateChange);
                loadBaselines();
                presenter.fireAggregate();
                populateReportsTable(true);
				$(DELAYSEC).val(REBOOT_DELAY_SEC); 
            };
            
            this.pause = function() {
            	if (timer) {
						clearInterval(timer);
						timer = null;
				}
                $('#hpsum-node-actions').show();                
                $('#hpsum-nodes-panel-selector').show();
                $(ADD_BASELINES).removeAttr("disabled");
                presenter.off("selectionChange", onSelectionChange);
                presenter.off("aggregateChange", onAggregateChange);
            };
             
            this.init = function() {
                $(ROOT + ' .hp-status').hpStatus();
                noItem = $(noneHtml);
                initNodeTable();
                initActionBaselineTable();
		mDeployDialogContents = $(MULTI_DEPLOY_DIALOG).detach().show();
                loadBaselines();
                $('#baselines-add').click(onAddBaselines);
                $(".hp-collapsible").hpCollapsible();
                $(".hp-select").selectBox({autoWidth: false});

                $(INVENTORY).on('click', function(ev) {
                    onInventory();
                    ev.preventDefault();
                });
		$(DEPLOY).on('click', function(ev) {
			onDeploy();
			ev.preventDefault();
		});
                $(APPLY).on('click', function(ev) {
                    onApply();
                    onsetoptiondetails();
                    ev.preventDefault();
                });

				$(GENERATE).live('click', function(ev) {
					 onGenerate.call();
					ev.preventDefault();
				});
				
				$('#hpsum-delete-report').live('click', function(ev) {
						deleteReportId = $(this).data("custom-value");
						onDeleteReport.call();
						ev.preventDefault();
				});
				this.resume(); 

            };
        }

        return new NodeShowOverviewView();
    }());
    
    return NodeShowOverviewView;
});
