// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (NodeShowReports)
 * This is a view class for Node Reports menu option.
 */

define(['hpsum/presenter/node/NodePresenter',
	'hpsum/presenter/ilofederation/iloFederationPresenter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/view/FormStateView',
    'hp/core/HelpMenu',
	'hp/core/Localizer',
	'hp/core/Notifications',
	'hp/view/DialogView',
	'hp/model/Session',
	'text!hpPages/core/header_help.html',
    'jquery',
    'hpsum/common/jquery.hpsumBrowse',
    'lib/jquery.selectBox'],
function(presenter, ilofederationPresenter, router,urlFragment, FormStateView, helpMenu, localizer, notifications, DialogView, session, headerHelpHtml) {"use strict";
	var report_output_path = '';
	var ReportsShowView = ( function() {
			var FORM = '#hpsum-nodes-reports-form',
			    RESET = '#hpsum-nodes-reset',
			    CANCEL = '#hpsum-nodes-reports-close',
			    GENERATE = '#hpsum-nodes-reports-generate',
			    TYPE = '#hpsum-node-reports-type',
			    ROUTE_PREFIX = '/node/reports',
				BROWSE_OK='#hp-report-add-ok',
				BROWSE_CANCEL='#browse-dialog-cancel',
				INFO_DIALOG = '#hpsum-info-dialog',
				BROWSE_LOCATION_ERROR = '#hpsum-invalid-location-error',
			    FIRMWARECHECKBOX = '#hpsum-node-reports-firmware',
			    INSTALLABLECHECKBOX = '#hpsum-node-reports-installable',
			    FAILEDDEPCHECKBOX = '#hpsum-node-reports-faileddep',
			    INSTALLEDCHECKBOX = '#hpsum-node-reports-installed',
			    INVENTORYCHECKBOX = '#hpsum-node-reports-inventory',
			    COMBINEDCHECKBOX = '#hpsum-node-reports-combined',
				FIRMWARETOOLTIP = '#hpsum-node-reports-firmware-label-tooltip',
				INSTALLABLETOOLTIP = '#hpsum-node-reports-installable-label-tooltip',
				FAILEDDEPTOOLTIP = '#hpsum-node-reports-faileddep-label-tooltip',
				INSTALLEDTOOTIP = '#hpsum-node-reports-installed-label-tooltip',
				COMBINEDTOOLTIP = '#hpsum-node-reports-combined-label-tooltip',
			    REPORTFORMATHTML = '#hpsum-node-reports-html',
			    REPORTFORMATXML = '#hpsum-node-reports-xml',
			    REPORTFORMATCSV = '#hpsum-node-reports-csv',
			    RUNBACKCHECKBOX = '#chkbox-runbackReport',
			    TITLE = '#hpsum-node-reports-title',
			    SPLASH_DIALOG = '#hpsum-report-wait-dialog',
			    SPLASH_SPINNER = '#hpsum-report-spinner',
			    REPORTS_TABLE = '#hpsum-reports-table',
				REPORTS_LOCATION = '#hpsum-reports-location',
				REPORTS_LOC_BROWSE = '#hpsum-report-browse-panel';

			function ReportsShowView() {
				var nodeItem = null,
				    timer = null,
				    inProgressTimer = null,
				    inProgressReportId = null,
				    reportWaitDialog,
					allReportsDialog,
				    deleteInfoDialog,
				    deleteReportId,
					infoDialog,
					instReportLocBrowse,
					rept_path,
				    generateInProgress = false;
				    
                function reset() {
                    var isBaseline = router.location().match(/baseline/i) ? false : true;
                    $(REPORTFORMATHTML).attr('checked', true);
                    $(INVENTORYCHECKBOX).attr('checked', true);
                    $(FIRMWARECHECKBOX).attr('checked', isBaseline);
                    $(FAILEDDEPCHECKBOX).attr('checked', isBaseline);
                    $(INSTALLABLECHECKBOX).attr('checked', isBaseline);                    
                    $(COMBINEDCHECKBOX).attr('checked', isBaseline);
                    $(RUNBACKCHECKBOX).attr('checked', false);
                    if ($(INSTALLEDCHECKBOX).is(':disabled')) {
                        $(INSTALLEDCHECKBOX).attr('checked', false)
                    }
                    else{
                        $(INSTALLEDCHECKBOX).attr('checked', isBaseline);
                    }

                    instReportLocBrowse.setPanelText(report_output_path);
					$('#hpsum-report-browse-panel-hpsumBrowse-input-text').attr('tooltip', report_output_path).hpTooltip();
				}
				
			function handleInvalidPath(hapi) {
				if (hapi.hcode == 5) {
					$(BROWSE_LOCATION_ERROR).html(localizer.getString('hpsum.baseline.add.inValidLocation'));
					instReportLocBrowse.addInputClass("hp-error");
					$(BROWSE_LOCATION_ERROR).show();
					$(GENERATE).attr("disabled", true);
				} else {
				    $(BROWSE_LOCATION_ERROR).hide();
				    instReportLocBrowse.removeInputClass("hp-error");
				}
			}

				function onItemChange(item) {
					if (timer) {
						clearInterval(timer);
						timer = null;
					}
					
					if(router.location().match(/baseline/i))
					   return;
					
					nodeItem = item.hapi;
					if (nodeItem && nodeItem.hasOwnProperty("node_id")) {
						$(TITLE).text(nodeItem.name);
						var arr = ["STAGE_ONLY_DONE", "INSTALLDONE"];
						if(($.inArray(nodeItem.node_state, arr) > -1 && !router.location().match(/one-touch-update/i)) 
							|| ((nodeItem.node_state.match(/UAN/i) || nodeItem.node_state.match(/ERROR/i)) && nodeItem.logs_available == true)){
						    //Disable installed reports
							 $(INSTALLEDCHECKBOX).removeAttr('disabled').attr('checked', true);
						} else {
							 $(INSTALLEDCHECKBOX).attr('checked', false).attr('disabled','disabled');
						}

						if(nodeItem.node_state.match(/REMOTE_STAGING_UAN/i) || nodeItem.node_state.match(/REMOTE_STAGING_SCHEDULED/i) 
							|| (nodeItem.node_state.match(/^SCHEDULED/i) && nodeItem.operation_mode != 0))
						{
							$(FIRMWARECHECKBOX).attr('checked', false).attr('disabled','disabled');
							$(INSTALLABLECHECKBOX).attr('checked', false).attr('disabled','disabled');
							$(FAILEDDEPCHECKBOX).attr('checked', false).attr('disabled','disabled');
							$(INVENTORYCHECKBOX).removeAttr('disabled').attr('checked', true);
							$(COMBINEDCHECKBOX).attr('checked', false).attr('disabled','disabled');
						}
						else
						{
							$(FIRMWARECHECKBOX).removeAttr('disabled').attr('checked', true);
							$(INSTALLABLECHECKBOX).removeAttr('disabled').attr('checked', true);
							$(FAILEDDEPCHECKBOX).removeAttr('disabled').attr('checked', true);
							$(COMBINEDCHECKBOX).removeAttr('disabled').attr('checked', true);

						}
					} else {
						$(CANCEL).trigger('click');
					}
				}

				function showReportGenerationWait() {

					var reportButtons = {};

					reportButtons[localizer.getString('hpsum.node.runbackReport')] = function() {
						if(router.location().match(/baseline/i)){
							notifications.show(localizer.getString("hpsum.node.runningReportInBack", new Array(nodeItem.baselinename)) + ' baseline. ' +
									 localizer.getString("hpsum.node.referForReportStatus"), 'ok');
							}
						else{
							notifications.show(localizer.getString("hpsum.node.runningReportInBack", new Array(nodeItem.name)) + ' .' +
								   localizer.getString("hpsum.node.referForReportStatus"), 'ok');
						}
						//clearInterval(timer);
						closesReportGenerationWait();
						//populateReportsTable(false);
						//$(GENERATE).attr("disabled", false);
					};

					if (!reportWaitDialog) {
						reportWaitDialog = $(SPLASH_DIALOG);
						reportWaitDialog.dialog({
							modal : true,
							dialogClass : 'hp-simple-dialog',
							position : "center",
							draggable : false,
							resizable : false,
							buttons : reportButtons,
							width : 400,
							height : 180
						});
					}
					$(SPLASH_SPINNER).show();
					reportWaitDialog.dialog('open');
				}

				function closesReportGenerationWait() {
					$(SPLASH_SPINNER).hide();
					if (reportWaitDialog) {
					   reportWaitDialog.dialog('close');
					}
				}

				function populateReportsTable(isItemOnChange) {	
					// In offline mode hide XML and CSV format report generation option which are not supported				
					var guimode = session.getProperty("gui_mode");
					if (guimode === "offline_automatic" || guimode === "offline_interactive" || guimode === "express") {

							$("#hpsum-node-reports-xml").parent().hide();
							$("#hpsum-node-reports-csv").parent().hide();
					}
				
					var reports = [],
					    firmware_report,
					    deploy_preview_report,
					    installed_report,
					    dependency_report,
					    inventory_report,
					    combined_report,
					    nodes = [],
					    scalableobjects=[];

					presenter.getAllReports({
						success : function(data) {
							reports = data.hapi.reports.report;
							var tableReports = [],
							    reportTypes = [],
							    reportStatus,
							    inProgress = false;

							    var tmp_path =  localizer.getString('hpsum.node.reportsLocationMessage') + data.hapi.reports.report_location;
								rept_path=data.hapi.reports.report_location;
								report_output_path = rept_path
								$(REPORTS_LOCATION).text(tmp_path); 
								instReportLocBrowse.setPanelText(rept_path);
							    
							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;
									generateInProgress = 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);
														generateInProgress = 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 = inventory_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-piano/throbber-small.png" class="hpsum-status-change-med">';
											} else { 	
								    		    firmware_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '-' + reports[idx].report_format + '.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-piano/throbber-small.png" class="hpsum-status-change-med">';
											} else { 
								    		    deploy_preview_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '-' + reports[idx].report_format + '.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-piano/throbber-small.png" class="hpsum-status-change-med">';
											} else { 
								    		    installed_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '-' + reports[idx].report_format + '.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-piano/throbber-small.png" class="hpsum-status-change-med">';
											} else { 
								    		    dependency_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '-' + reports[idx].report_format + '.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] == "inventory_report") {
                                            reportTypes[i] = "Inventory";
                                            if (inProgress) {
                                                inventory_report = '<img src="/img/hp-piano/throbber-small.png" class="hpsum-status-change-med">';
                                            } else { 
                                                inventory_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '-' + reports[idx].report_format + '.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-piano/throbber-small.png" class="hpsum-status-change-med">';
                                            } else { 
                                                combined_report =  '<a href="' + reports[idx].report_id + '/' + reportTypes[i] + '-' + reports[idx].report_format + '.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-nodes-delete-report" data-custom-value="' + reports[idx].report_id + '-' + reports[idx].report_format + '">' +
								'<img src="/img/hp-piano/close.png" >' + '</a>';
								
								tableReports.push({
									time_stamp : reports[idx].date_and_time,
									report_path:reports[idx].report_path,
									report_format : reports[idx].report_format,
									firmware_type : firmware_report,
									deploy_preview_type : deploy_preview_report,
									installed_type : installed_report,
									dependency_type : dependency_report,
									inventory_type: inventory_report,
									combined_report: combined_report,
									report_status : reportStatus,
									node_name : reports[idx].node_id,
									delete_report : deleteReport
								});
							}
	
							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() {
								}
							}); 

							ilofederationPresenter.getAllScalableObjects({
								success: function(data){
									 console.log(data);
									 scalableobjects = data.hapi.output_data.scalable_groups.scalable_group;

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

									$(REPORTS_TABLE).dataTable().fnClearTable();
									$(REPORTS_TABLE).dataTable().fnAddData(tableReports);
								},
								error: function(data){

								}
							})

									    
							$(REPORTS_TABLE).dataTable().fnClearTable();
							$(REPORTS_TABLE).dataTable().fnAddData(tableReports);
						},
						error : function(data) {
							notifications.show(localizer.getString("hpsum.node.failedReport", new Array(nodeItem.name)), 'error');
							$(CANCEL).trigger('click');
						}
					});
				};

					
				function onGenerate() {
					
					generateInProgress = true;
					
					$(GENERATE).attr("disabled", true);
					
					if (!$(RUNBACKCHECKBOX).is(':checked')) {
						showReportGenerationWait();
					}

					var request, reportformat = "";

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

					var firmwaretype = $(FIRMWARECHECKBOX).is(':checked');
					var deploy_previewtype = $(INSTALLABLECHECKBOX).is(':checked');
					var faileddeptype = $(FAILEDDEPCHECKBOX).is(':checked');
					var installedtype = $(INSTALLEDCHECKBOX).is(':checked');
					var inventorytype = $(INVENTORYCHECKBOX).is(':checked');
					var combinedtype = $(COMBINEDCHECKBOX).is(':checked');
					//Since we are using a common UI screen for reports
					//set a flag to indicate if the report was requested
					//from the baseline screen to generate inventory reports
					var isBaselineReport = "false";
					var nodeId, request, currentLocation = router.location();
					if (currentLocation.match(/one-touch-update/i) ) {
						nodeId = "N1localhost";
						nodeItem = {name: "localhost"};
					}
					else if(currentLocation.match(/baseline/i)){
						isBaselineReport = "true";
						var baseline = currentLocation.split('/');
						var baselineId = "";
						var locationId = "";
						if (baseline.length > 10){
							baselineId = baseline[baseline.length-2];
						}
						
						if (baseline.length > 10){
							locationId = baseline[baseline.length-4];
						}
						
						request = { 
							hapi : {
								report_format : reportformat,
								inventory_report : isBaselineReport,
								baselines : {
									baseline : {
										baseline_id : baselineId,
										location_id : locationId										
									}
								}
							}
						};
					}
					else{
						if (nodeItem && nodeItem.hasOwnProperty("node_id")) {
							nodeId = nodeItem.node_id;
							request = {
								 hapi : {
									report_format : reportformat,
									inventory_report: isBaselineReport,
									nodes : {
										node : {
											node_id : nodeId,	
											firmware_report : firmwaretype,
											deploy_preview_report : deploy_previewtype,
											dependency_report : faileddeptype,
											installed_report : installedtype,
											inventory_report : inventorytype,
											combined_report : combinedtype
										}
									}
								}
							};
						}
						else {
							nodeItem = {name: "localhost"};
							nodeId = "N1localhost";	
						}
					}
					
					
					
					var requestSetSessionAttribute = {
						hapi : {
							report_dir : instReportLocBrowse.getLocation() 
							}
					};
					
					if ( rept_path.toLowerCase() != instReportLocBrowse.getLocation().toLowerCase() ) {
					presenter.setSessionAttribute(requestSetSessionAttribute, {
						success : function(data) {
							createRepPresenter(request)	;
					
						},
						error : function(errorInfo) {
							closesReportGenerationWait();
							$(BROWSE_LOCATION_ERROR).show();
							$(BROWSE_LOCATION_ERROR).html(localizer.getString('hpsum.baseline.add.inValidLocation'));
							instReportLocBrowse.addInputClass('hp-error');
							$(GENERATE).attr("disabled", true);
							generateInProgress = false;
							}
						});
					}
					else
					{
						createRepPresenter(request)	;
					}
				}
				
				function createRepPresenter(request)
				{
					presenter.createReport(request, {
						success : function(data) {
							onSuccessReportCreation(data.hapi.report_id);
						},
						error : function(errorInfo) {
							notifications.show(errorInfo, 'error');
							closesReportGenerationWait();
							$(CANCEL).trigger('click');
						}
					});
				}

				function getReportStatus(reportId) {
					
					if (timer) {
						clearInterval(timer);
						timer = null;
					}

					//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/i)) {
								} 
								else if (data.hapi.report_state.match(/report_generation_completed/i)) {
									if (router.location().match(/baseline/i)){
										notifications.show(localizer.getString("hpsum.node.doneReport",new Array(data.hapi.report_id)) + ' baseline.', 'ok');
									}
									else{
										notifications.show(localizer.getString("hpsum.node.doneReport", new Array(nodeItem.name)) + '.' , 'ok');
									}
									closesReportGenerationWait();
									//clearInterval(timer);
								
									if (timer) {
										clearInterval(timer);
										timer = null;
									}

									$(GENERATE).attr("disabled", false);
									populateReportsTable(false);
									generateInProgress = false;
									//status = "";
									//changeLocation('/node/reports/allAvailableReports');
								} else if (data.hapi.report_state.match(/partially_generated/i)) {
									//notifications.show(localizer.getString("hpsum.node.partialReport", new Array(nodeItem.name)), 'warning');
									//closesReportGenerationWait();
									//clearInterval(timer);
									//$(GENERATE).attr("disabled", false);
									//populateReportsTable();
									//status = "";
									//changeLocation('/node/reports/allAvailableReports');
									
								} else {
									notifications.show(localizer.getString("hpsum.node.failedReport", new Array(nodeItem.name)), 'error');
									closesReportGenerationWait();
									
									if (timer) {
										clearInterval(timer);
										timer = null;
									}

									$(CANCEL).trigger('click');
								}
							 //}
							},
							error : function(errorInfo) {
								notifications.show(errorInfo, 'error');
								closesReportGenerationWait();
								
								if (timer) {
									clearInterval(timer);
									timer = null;
								}

								$(CANCEL).trigger('click');
							}
						});

					}, 3000);
				}

				function onSuccessReportCreation(reportId) {
					//$(GENERATE).attr("disabled", false);
					populateReportsTable(false);
					presenter.generateReport(reportId, {
						success : function(data) {
							if (!$(RUNBACKCHECKBOX).is(':checked')) {
								populateReportsTable(false);
								getReportStatus(reportId);
							} 
							else if(router.location().match(/baseline/i)){
								notifications.show(localizer.getString("hpsum.node.runningReportInBack", new Array(nodeItem.baselinename)) + ' baseline. ' +
									 localizer.getString("hpsum.node.referForReportStatus"), 'ok'); 
									 populateReportsTable(false);
								getReportStatus(reportId);
							}
							else {
								notifications.show(localizer.getString("hpsum.node.runningReportInBack",new Array(nodeItem.name)) + ' .' +
											 localizer.getString("hpsum.node.referForReportStatus"), 'ok');
							    populateReportsTable(false);
								//$(GENERATE).attr("disabled", false);
								getReportStatus(reportId);
							}
						},
						error : function(errorInfo) {
							notifications.show(errorInfo, 'error');
							closesReportGenerationWait();
							$(CANCEL).trigger('click');
						}
					});
				}

				function onDeleteReport() {
                              
                              if (!deleteInfoDialog) {
                                    deleteInfoDialog = $('#hpsum-delete-report-dialog');
                                    deleteInfoDialog.dialog({
                                          autoOpen: false,
                                          show: {
                                                effect: "slide",
                                                duration: 10
                                          },
                                          modal : true,
                                          dialogClass : 'hp-simple-dialog',
                                          position : "center",
                                          draggable : false,
                                          resizable : false,
                                          buttons : [{
                                    text: localizer.getString('hpsum.baseline.show.yesDelete'),
                                    class: 'hp-primary',
                                    click: 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');
                                    }}, {
                                    text: localizer.getString('hpsum.common.button.cancel'),
                                    click: function(){
                                          deleteInfoDialog.dialog('close');
                                    }
                                }]
                                    });
                              }
                              
                              deleteInfoDialog.dialog('open');    
                        }

				

			
			function showInfoDialog()
            {
            	if (!infoDialog) {
                    infoDialog =  $(INFO_DIALOG);
                    infoDialog.dialog({
                        modal : true,
                        dialogClass: 'hp-simple-dialog',
                        position : "center",
                        draggable : false,
                        resizable : false
                    });
                    $('button', infoDialog).on('click', function () {
                        infoDialog.dialog('close');
                    });
                }
                infoDialog.dialog('open');
            }
            
            function onNoSelection(){
            	showInfoDialog();	
            }
           
               	function onReportLocationChange(){
					$(GENERATE).attr("disabled", true);
					if(generateInProgress){
						return;
					}
					
					var path= instReportLocBrowse.getLocation();
					var reportDirName = "";
					var illegalfoldernamewithdot = /^\./g; // cannot start with dot (.)  
					var illegalcharcatersTest = "";
					if ( navigator.appVersion.indexOf("Win") != -1 ){
						reportDirName = path.substring(path.lastIndexOf('\\')+1);						
						illegalcharcatersTest = /[/.:|\?|\\|\*|\"|<|>|\||%\s\*]/g; //cannot start with space ("") and no illegal charctaers(/ \   “ * / : < > |) in directory name
					}
					else{
						reportDirName = path.substring(path.lastIndexOf('/')+1);
						illegalcharcatersTest = /[.:|\?|\\|\*|\"|<|>|\||%\s\*]/g; //cannot start with space ("") and no illegal charctaers(/ \   “ * / : < > |) in directory name
					}
					
					if(illegalfoldernamewithdot.test(reportDirName) || illegalcharcatersTest.test(reportDirName))
					{
						$(BROWSE_LOCATION_ERROR).show();
						$(BROWSE_LOCATION_ERROR).html(localizer.getString('hpsum.baseline.add.emptyReportText'));
						instReportLocBrowse.addInputClass('hp-error');							
					}
					else
					{
						$(BROWSE_LOCATION_ERROR).hide();						
						instReportLocBrowse.removeInputClass('hp-error');
						if ( $(INVENTORYCHECKBOX).is(':checked') || $(FIRMWARECHECKBOX).is(':checked') ||
							 $(INSTALLABLECHECKBOX).is(':checked') || $(FAILEDDEPCHECKBOX).is(':checked') ||
							 $(INSTALLEDCHECKBOX).is(':checked') || $(COMBINEDCHECKBOX).is(':checked') )
						{
							// If directory path is empty or undefined just disable generate button
							if (path == undefined || path.length == 0){
								$(GENERATE).attr("disabled", true);
							}
							else {
								$(GENERATE).attr("disabled", false);
							}
						}
					}
				}
				function checkNoneReportTypeChecked(){
					onReportLocationChange();
				}	

				this.init = function() {
				
				$('#hpsum-report-location-text').html(localizer.getString('hpsum.baseline.add.browseReportText'));
				$('#hpsum-report-location-text').removeClass('hp-collapsed');
				
               	var options = 	{
									command : 'init',
									panelLabel: "hpsum.baseline.add.enterDirectory",
									panelLabelStyle: "padding-left: 33px;",
						            panelHelp: "",
						            panelBrowseText: "hpsum.common.browse",
									bShowEmptyFolder: false,
						            onNoSelection: onNoSelection
						        };
				$(REPORTS_LOC_BROWSE).hpsumBrowse(options);
				$('#hpsum-report-browse-panel-hpsumBrowse-input-text').attr('style', 'width:450px;');
				instReportLocBrowse = $(REPORTS_LOC_BROWSE).data('plugin_hpsumBrowse');
				
				instReportLocBrowse.setInputEvent("onkeyup", onReportLocationChange);
				instReportLocBrowse.setInputEvent("onchange", onReportLocationChange);
				instReportLocBrowse.setInputEvent('onfocusout', onReportLocationChange);
				instReportLocBrowse.setInputEvent('onfocus', onReportLocationChange);
               
					var resource = router.location().split('/');
                	resource = resource[1];
              	$('a[data-panel-id]').each(function(index) {
                		var currentLink = $(this).attr('href');
                		if(currentLink  == undefined)
                			return;
                		var current = currentLink.split('/');
				$('#hpsum-node-reports-firmware').attr('tooltip', localizer.getString('hpsum.node.firmwareDetailshelp')).hpTooltip();
				$('#hpsum-node-reports-combined').attr('tooltip', localizer.getString('hpsum.node.combinedReporthelp')).hpTooltip();
				$('#hpsum-node-reports-faileddep').attr('tooltip', localizer.getString('hpsum.node.failedDependencyDetailshelp')).hpTooltip();
				$('#hpsum-node-reports-installable').attr('tooltip', localizer.getString('hpsum.node.installableDetailshelp')).hpTooltip();
				$('#hpsum-node-reports-installed').attr('tooltip', localizer.getString('hpsum.node.installedDetailshelp')).hpTooltip();
				$('#hpsum-node-reports-inventory').attr('tooltip', localizer.getString('hpsum.node.inventoryhelp')).hpTooltip();
				$('#hpsum-node-reports-html').attr('tooltip', localizer.getString('hpsum.node.htmlhelp')).hpTooltip();
				$('#hpsum-node-reports-csv').attr('tooltip', localizer.getString('hpsum.node.csvhelp')).hpTooltip();
				$('#hpsum-node-reports-xml').attr('tooltip', localizer.getString('hpsum.node.xmlhelp')).hpTooltip();
				$('#chkbox-runbackReport').attr('tooltip', localizer.getString('hpsum.node.runbackReporthelp')).hpTooltip();
						
                		current[1] = resource;
                		currentLink =current.join('/');
                		$(this).attr('href',currentLink);
  					});
  					ROUTE_PREFIX = '/'+ resource +'/reports';

					$(RESET).live('click', function() {
						reset.call();
						onReportLocationChange();
					});

					$(GENERATE).live('click', function(ev) {
						var path= instReportLocBrowse.getLocation(); 
						if (!generateInProgress && path != "") {
						 onGenerate.call();
						}
						else
						$(GENERATE).attr("disabled", true);
						ev.preventDefault();
					});
					
					$(INVENTORYCHECKBOX).on('click', function(ev) {
						checkNoneReportTypeChecked.call();
					});
					$(FIRMWARECHECKBOX).on('click', function(ev) {
						checkNoneReportTypeChecked.call();
					});
					$(INSTALLABLECHECKBOX).on('click', function(ev) {
						checkNoneReportTypeChecked.call();
					});
					$(FAILEDDEPCHECKBOX).on('click', function(ev) {
						checkNoneReportTypeChecked.call();
					});
					$(INSTALLEDCHECKBOX).on('click', function(ev) {
						checkNoneReportTypeChecked.call();
					});
					$(COMBINEDCHECKBOX).on('click', function(ev) {
						checkNoneReportTypeChecked.call();
					});
					
					$('#hpsum-nodes-delete-report').live('click', function(ev) {
						deleteReportId = $(this).data("custom-value");
						onDeleteReport.call();
						ev.preventDefault();
					});
					
					// put help in header
					if ($('.hp-details-header-controls', $(FORM).parent()).length === 0) {
						var headerHelp = $(headerHelpHtml);
						localizer.localizeDom(headerHelp);
						$('.hp-details-header', $(FORM).parent()).append(headerHelp);
					}
					
					$(CANCEL).click(function () {
					if (timer) {
						clearInterval(timer);
						timer = null;
					}
					if (inProgressTimer) {
						clearInterval(inProgressTimer);
						inProgressTimer = null;
					}
					
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                });
					router.watch('node report section', ROUTE_PREFIX + '.*', {
						parent : ROUTE_PREFIX,
					});
					
					this.resume();
				};

				this.resume = function() {
				    presenter.on("itemChange", onItemChange);
				    ilofederationPresenter.on("itemChange", onItemChange);
					var guimode = session.getProperty("gui_mode");
               				if(guimode === "offline_automatic" || guimode === "offline_interactive" || guimode === "express")
					{
						//Disable installed reports						
						$(REPORTFORMATXML).attr('checked', false).attr('disabled','disabled');
						$(REPORTFORMATCSV).attr('checked', false).attr('disabled','disabled');
					} 
					else
					{         
						//Enable installed reports
						 $(REPORTFORMATXML).removeAttr('disabled');
						 $(REPORTFORMATCSV).removeAttr('disabled');
					}					
					var dummyReportsData = [];
					$(REPORTS_TABLE).dataTable({
						oLanguage : {
						    sEmptyTable: localizer.getString("hpsum.node.noReports"),
						    sSearch: localizer.getString('hpsum.common.search')
						},
						bPaginate : false,
						bFilter : false,
						bInfo : false,
						bAutoWidth : false,
						bRetrieve : true,
						bDestroy : true,
						aaData : dummyReportsData,
						aoColumns : [{
							mDataProp : 'time_stamp'
						},{
							mDataProp : 'report_path'
						},{
							sWidth: 75, mDataProp : 'firmware_type'
						},{
							sWidth: 75, mDataProp : 'deploy_preview_type'
						},{
							sWidth: 75, mDataProp : 'installed_type'
						},{
							sWidth: 75, mDataProp : 'dependency_type'
						},{
                            sWidth: 75, mDataProp : 'inventory_type'
                        },{
                            sWidth: 75, mDataProp : 'combined_report'
                        },{
							mDataProp : 'report_format'
						},{
							mDataProp : 'node_name'
						},{
							mDataProp : 'report_status'
						},{
							mDataProp : 'delete_report'
						}],
						aaSorting: [[ 0, "desc" ]]
					});
					
					generateInProgress = false;
					if (timer) {
						clearInterval(timer);
						timer = null;
					}
					if (inProgressTimer) {
						clearInterval(inProgressTimer);
						inProgressTimer = null;
					}
					
					$(RESET).trigger('click');
					$(GENERATE).attr("disabled", false);
					$(BROWSE_LOCATION_ERROR).hide();
					instReportLocBrowse.removeInputClass('hp-error');
					populateReportsTable(true);
					
					if(router.location().match(/baseline/i)) {
                        //Disable all report except inventory
						$('#hpsum-node-reports-firmware-label').hide();
						$('#hpsum-node-reports-installable-label').hide();
						$('#hpsum-node-reports-faileddep-label').hide();
						$('#hpsum-node-reports-installed-label').hide();
						$('#hpsum-node-reports-combined-label').hide();
                        $(FIRMWARECHECKBOX).attr('checked', false).hide();
                        $(INSTALLABLECHECKBOX).attr('checked', false).hide();
                        $(FAILEDDEPCHECKBOX).attr('checked', false).hide();
                        $(INSTALLEDCHECKBOX).attr('checked', false).hide();
                        $(COMBINEDCHECKBOX).attr('checked', false).hide();
						$(FIRMWARETOOLTIP).hide();
						$(INSTALLABLETOOLTIP).hide();
						$(FAILEDDEPTOOLTIP).hide();
						$(INSTALLEDTOOTIP).hide();
						$(COMBINEDTOOLTIP).hide();
						$('#hpsum-node-reports-formats').attr('style','position:relative;bottom:280px;');
                    }
				};

				this.pause = function() {
					
					if (timer) {
						clearInterval(timer);
						timer = null;
					}
					presenter.off("itemChange", onItemChange);
					ilofederationPresenter.off("itemChange", onItemChange);
				};

			}

			return ReportsShowView;
		}());

	return new ReportsShowView();

});



