// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * This provides login and logout functions with dummy session details.
 * Set and retrieval functions for GlobalSettings provided here.
 */
define([ 'hp/model/Session',
         'hp/view/DialogView',
         'hp/core/Localizer',
         'hp/services/Log',
         'text!hpsumpages/common/logoff_shutdown.html', 
         'text!hpsumpages/common/thankyou.html',
         'jquery',
         'hpsum/hpsum-version'], function(session, DialogView, localizer, Log, logoffhtml,thankyouhtml) {

             var SHUTDOWN = '#hpsum-shutdown';
             var LOGOFF = '#hpsum-logoff';
             var authTokenValue = "";
	var SHUTDOWN_LIST = '#hp-schedule-nodes-list';
	var OK = '#hpsum-action-ok';
	var closeHandler;
	var WARNING_MESSAGE = '#hpsum-logoff-warning-message'; /* to set text for the warning message to be shown */
	function logOffSession(handlers) {

		var value = $('input[name=hpsum-logoff-value]:checked').val();
		var logoffdialogcontents = $(logoffhtml);
		if(value == "closebrowserconnection")
		{
			thankyouhtml = thankyouhtml.replace(/%1/gi, hpsumShortVersionStr);
			thankyouhtml = thankyouhtml.replace(/@shutdown@/gi, localizer.getString("hpsum.thankyou.closeBrowserConnection"));
			thankyouhtml = thankyouhtml.replace(/@thankyou@/gi, " "); /* No need to use the hpsum.thankyou.thank */
			thankyouhtml = thankyouhtml.replace(/@referencevid@/gi, localizer.getString("hpsum.thankyou.reference_videos"));
			var styleSheetsNeeded = $(thankyouhtml).styleSheets;
			thankyouhtml = thankyouhtml.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
			var styleSheets = document.styleSheets;
			for (var idx = 0; idx < styleSheets.length; idx++) {
				styleSheets[idx].disabled = true;
			}
			window.document.body.innerHTML = thankyouhtml;
			window.document.styleSheets = styleSheetsNeeded;
			
			$('#hpsum-closedbrowser-reload').show();
			return;
		}
		var closeHandlers = { 
				success:function(data)
						{
							var styleSheetsNeeded = "";
							if(data.hapi.hcode == 4002)
							{
								var nodes = [], table;
								nodes = data.hapi.nodes.node;
								var contents = $(logoffhtml);
								localizer.localizeDom(contents);
								table = "<fieldset><ol><li><p style='font-size:14px;color:red;margin: 10px;'>" + localizer.getString('hpsum.node.shutdownNodeError') + "</p></li>";
                                table += "<li><p style='font-size:14px;color:red;margin: 10px;'>" + data.hapi.hmessage + "</p></li>";
                              
								table += "<li><table><thead><tr><th><b>" + localizer.getString('hpsum.menu.node') + "</b></th><th><b>" + localizer.getString('hpsum.common.username') + "</b></th></tr> ";
								for (var idx = 0; idx < nodes.length; idx++) 
								{
									table += "<tr><td>" + '<a id="hpsum-shutdown-node-click" class="company-a" href="#/node' + '/show/r/Session/' + nodes[idx].node_session + '/node/' + nodes[idx].node_id + '/getdata">' + nodes[idx].node_name + '</a>';
									table += "<td>" + nodes[idx].user_name + "</td></tr>";
								}
								
								table += "</table></li></ol></fieldset>";
								$(OK).hide();
								$(SHUTDOWN_LIST).html(table);
								// When there more than 15 items then OK, Cancel not visible at bottom hence changing the hight otherwise automatically resizes
								if (nodes.length > 15){
									$(SHUTDOWN_LIST).css('height','450px');
								}
							}
							else if(data.hapi.hcode == 4003)
							{
								var table;
								var contents = $(logoffhtml);
								localizer.localizeDom(contents);
								table = "<fieldset><ol><li><p style='font-size:14px;color:red;margin: 10px;'>" + "</p></li>";
                                table += "<li><p style='font-size:14px;color:red;margin: 10px;'>" + data.hapi.hmessage + "</p></li>";
								table += "</table></li></ol></fieldset>";
								$(OK).hide();
								$(SHUTDOWN_LIST).html(table);
							}
							else if(data.hapi.hcode == 4001)
							{
								var table;
								var contents = $(logoffhtml);
								localizer.localizeDom(contents);
								table = "<fieldset><ol><li><p style='font-size:14px;color:red;margin: 10px;'>" + data.hapi.hmessage + "</p></li></ol></fieldset>"; 
								$(OK).hide();
								$(SHUTDOWN_LIST).html(table);
							}
							else if(data.hapi.hcode == 5000)
							{
								var nodes = [], table;
								nodes = data.hapi.nodes.node;
								var contents = $(logoffhtml);
								localizer.localizeDom(contents);
								table = "<fieldset><ol>";
                                table += "<li><p style='font-size:14px;color:red;margin: 10px;'>" + data.hapi.hmessage + "</p></li>";
								table += "<li><table><thead><tr><th><b>" + localizer.getString('hpsum.common.commandStr') + "</b></th><th><b>" + localizer.getString('hpsum.common.statusStr') + "</b></th></tr> ";
								for (var idx = 0; idx < nodes.length; idx++) 
								{
									table += "<tr><td>" + nodes[idx].command + " </td><td>" + nodes[idx].status + "</td></tr>";
								}
								
								table += "</table></li></ol></fieldset>";
								$(OK).hide();
								$(SHUTDOWN_LIST).html(table);
								// When there more than 15 items then OK, Cancel not visible at bottom hence changing the hight otherwise automatically resizes 
								if (nodes.length > 15){
									$(SHUTDOWN_LIST).css('height','450px');
								}
							}
							else {
								session.eraseAll();
								if (handlers && handlers.success) {
									handlers.success({});
								}
								if(value =='shutdown'){
									session.eraseManufacturer();
									thankyouhtml = thankyouhtml.replace(/%1/gi, hpsumShortVersionStr);
                                    thankyouhtml = thankyouhtml.replace(/@shutdown@/gi, localizer.getString("hpsum.thankyou.shutdown"));
                                    thankyouhtml = thankyouhtml.replace(/@thankyou@/gi, localizer.getString("hpsum.thankyou.thank"));
                                    thankyouhtml = thankyouhtml.replace(/@referencevid@/gi, localizer.getString("hpsum.thankyou.reference_videos"));
									styleSheetsNeeded = $(thankyouhtml).styleSheets;
									thankyouhtml = thankyouhtml.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
									var styleSheets = document.styleSheets;
									for (var idx = 0; idx < styleSheets.length; idx++) {
										styleSheets[idx].disabled = true;
									}
									window.document.body.innerHTML = thankyouhtml;
									window.document.styleSheets = styleSheetsNeeded;
									$('#hpsum-closedbrowser-reload').hide();
								}
								else
								{
									window.location.hash = '#/login';
									window.location.reload(true);
								}
							}
						},
			    error:function(){
			         Log.error("Error shutting down the engine");
			      }
		};
		
		$(SHUTDOWN, logoffdialogcontents).off('click').on("click", function () {
		    $.ajax({
		        url: "/session/" + authTokenValue + "/node/index",
		        type: 'GET',
		        contentType: "application/json",
		        dataType: "json",
		        success: closeHandler.success,
		        error: closeHandler.error,
		        headers: {
		            "Accept-language": '',
		            "Session-ID": authTokenValue,
		            "Session-KeepAlive": true
		        }
		    });

		});

		$(LOGOFF, logoffdialogcontents).off('click').on("click", function () {
		    var value = $('input[name=hpsum-logoff-value]:checked').val();
		    if (value == "logoff") {
		        $(OK).show();
		        $(SHUTDOWN_LIST).html("");
		    }

		});
		new DialogView({
		    contents : logoffdialogcontents,
		    ok: function () {
		        logOffSession(handlers);
		    },
		    cancel: function () {
		        return;
		    }

		});
		if(value == 'closebrowserconnection')
		{

		}
		else if (value == 'logoff') {
			//close hpsum session
			session.closeSession(closeHandlers);
		} else {
			var data = { hapi: {
						force: 'false'
						}};
			session.shutDown(data,closeHandlers);
			Log.info("initiated shutdown");
		}
		
		
	}


	var sessionGetTaskCountHandlers = {
		success:function(data)
		{
			
			var nTasks = data.hapi.number_of_tasks_running;
			var warningMessage;
			if(nTasks != 0)
			{
				warningMessage = localizer.getString('hpsum.common.status.warning') + " : " + nTasks + localizer.getString('hpsum.logout.logoutWarningMessage2');	
			}
			else
			{
				warningMessage = localizer.getString('hpsum.logout.zeroScheduled');
			}
		    //$(WARNING_MESSAGE).show(); // commenting this option as we are hiding scheduling feature in 8.0.0. it should be uncommneted when we re-enable scheduling.
			$(WARNING_MESSAGE).text(warningMessage);

		},
		error:function(data)
		{
			

		}

	};

	//TODO convert to module pattern
	return {
		login : function(username, password, provider, handlers) {

			session.createSession(username, password, handlers);
		},
        logout : function (authToken, handlers) {
            authTokenValue = authToken;
			var logoffdialogcontents = $(logoffhtml);
			localizer.localizeDom(logoffdialogcontents);
			session.getSessionData(sessionGetTaskCountHandlers);
			closeHandler = {
															
						success : function(data) {
							var nodes = [], table, sched_flag = "no";
							nodes = data.hapi.output_data.nodes.node;
							if(nodes)
							{
								var contents = $(logoffhtml);
								localizer.localizeDom(contents);
								table = "<p>"+localizer.getString('hpsum.node.shutdownNodeDeploy')+"</p>";
								table += "<table><thead><tr><th><b>" + localizer.getString('hpsum.group.nodeName') + "</b></th><th><b>" + localizer.getString('hpsum.group.scheduledatetime') + "</b></th></tr> ";
								for (var idx = 0; idx < nodes.length; idx++) 
								{
									if (nodes[idx].node_phase.match(/Scheduled/i) && nodes[idx].node_state.match(/SCHEDULED/i))
									{   
										// var schedule_date_time_old = nodes[idx].schedule_date_time.split(' ');
										// var schedule_time_format = schedule_date_time_old[2];
										// var schedule_time = schedule_date_time_old[1];
										// var schedule_time_hrs_mins = schedule_time.split(':');
										// var schedule_time_hrs = schedule_time_hrs_mins[0];
										// var schedule_date_time_new;
										// if(schedule_time_format == 'PM')
										// {
										// 	if (schedule_time_hrs < 12)
										// 	{
										// 		schedule_time_hrs = parseInt(schedule_time_hrs) + 12;
										// 		schedule_date_time_new = schedule_date_time_old[0] + ' ' + schedule_time_hrs + ':' + schedule_time_hrs_mins[1];
										// 	}
										// 	if (schedule_time_hrs == 12)
										// 	{
										// 		schedule_time_hrs = parseInt(schedule_time_hrs) + 0;
										// 		schedule_date_time_new = schedule_date_time_old[0] + ' ' + schedule_time_hrs + ':' + schedule_time_hrs_mins[1];
										// 	}
										// }
										// if(schedule_time_format == 'AM')
										// {
										// 	if (schedule_time_hrs < 12)
										// 	{
										// 		schedule_time_hrs = parseInt(schedule_time_hrs) + 0;
										// 		if(schedule_time_hrs < 10)
										// 			schedule_date_time_new = schedule_date_time_old[0] + ' ' + '0' +schedule_time_hrs + ':' + schedule_time_hrs_mins[1];
										// 		else
										// 			schedule_date_time_new = schedule_date_time_old[0] + ' ' +schedule_time_hrs + ':' + schedule_time_hrs_mins[1];
										// 	}
										// 	if (schedule_time_hrs == 12)
										// 	{
										// 		schedule_time_hrs = parseInt(schedule_time_hrs) - 12;
										// 		schedule_date_time_new = schedule_date_time_old[0] + ' ' + '0'+ schedule_time_hrs + ':' + schedule_time_hrs_mins[1];
										// 	}
										// }
										// table += "<tr><td>" + nodes[idx].node_name + "</td>";
										// table += "<td>" + schedule_date_time_new + "</td></tr>";
										// sched_flag = "yes";
									}
								}
								table += "</table>";
								if(sched_flag == "yes")
									$(SHUTDOWN_LIST).html(table);
							}
							else
							{
							}
						},
						error : function() {
						}
					};
			$(SHUTDOWN,logoffdialogcontents).on("click" ,function() 
			{
			
							$.ajax({	url : "/session/" + authToken + "/node/index",
										type : 'GET',
										contentType : "application/json",
										dataType : "json",
										success : closeHandler.success,
										error : closeHandler.error,
										headers : {
											"Accept-language" : '',
											"Session-ID" : authToken,
											"Session-KeepAlive": true
										}
									});
					 
			});

			$(LOGOFF, logoffdialogcontents).on("click", function ()
			{
			    var value = $('input[name=hpsum-logoff-value]:checked').val();
			    if (value == "logoff") {
			        $(OK).show();
			        $(SHUTDOWN_LIST).html("");
			    }

			});

			new DialogView({
				contents : logoffdialogcontents,
				ok : function() {
					logOffSession(handlers);
				},
				cancel : function() {
					return;
				}
				
			});
        },
		getGlobalSettings : function (handlers) {
            setTimeout(function() {
                handlers.success({"allowLocalLogin":true,"defaultLoginDomain":{"name":"LOCAL","uri":"","loginDomain":"0"},"configuredLoginDomains":[]});
            }, 10)
        },
        setGlobalSettings : function (allowLocalLogin, defaultProviderId, handlers) {
            //REST.putObject('/authn/rest/authentication/globalsettings',
            //        {"allowLocalLogin": allowLocalLogin, "defaultProvider":{"providerId": defaultProviderId}},
            //        null, handlers);
            handlers.error({errorMessage: "authn.setGlobalSettings() not Implemented"})
        }
    };
});
