//                                    OM
/******************************************************************************
 * @file jquery.hpsumSchedule.js
 *
 *
 * @section LICENSE
 *
 * HPE Confidential
 * Copyright 2015 Hewlett-Packard Enterprise Company, L.P.
 *
 * @section DESCRIPTION
 *
 * Schedule plugin
 *
 *******************************************************************************/

define(['hp/core/Localizer',
		'hp/services/Log',
        'jquery',
        'hp/lib/jquery.hpStatus',
        'hpsum/common/jquery.hpsumdatetime',
        'lib/jquery-ui-timepicker-addon',
        'hp/lib/jquery.hpToggle'],
function(localizer,log) {
    "use strict";
    //Lets create the plugin.
    (function($) {
    	var STAGE_SCHEDULE_DATETIMEPICKER = '#stage-schedule-datetimepicker',
			RUN_NOW = '#hpsum-run-immediatly',
			SCHEDULE_OPTION = '#hpsum-schedule-option',
			SCHEDULE_DETAILS = '#hpsum-schedule-details',
			STAGE_NOTE = '#hpsum-stage-note',
			SCHEUDLE_FROM_ERR = '#hpsum-schedule-from-error',
			SCHEUDLE_TO_ERR = '#hpsum-schedule-to-error',
			MASTER_NODE_TIME = "#hpsum-masternode-time",
			SCHEUDLED_DATE_TIME,
			OK;
		var today;
		var idPrepender;
		var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

        //Adding the plugin as jquery extension.
        $.fn.hpsumSchedule = function(options) {

        		function SchedulePlugin(pelement , options)
        		{
        			var _this = this;
        			this.parentElement = pelement;
        			this.options = options;
        			this.t = null;
        			this.input_id1 = 'stage-schedule-datetimepicker-' + uuid();
					this.input_id2 = 'stage-schedule-datetimepicker-' + uuid();
                    this.master_node_current_time  = new Date();
					this.scheduled_date_time = "";

        			this.init = function()
        			{
        				var container   = this.parentElement;

						var html = '<h3 rel="localize[hpsum.node.scheduling]">Scheduling</h3>'+
									'<ol>'+
										'<li>' +
										'<input id="hpsum-run-immediatly" type="radio" name="hpsum-schedule-options" value="one" checked="checked"> '+
										'<label for="hpsum-run-immediatly" style="margin-top: 10px; max-width: 500px" rel="localize[hpsum.server.runnow]">Run Now (no schedule)</label>'+
										'</li>'+
										'<li>'+
											'<input id="hpsum-schedule-option" type="radio" name="hpsum-schedule-options" value="two"> '+
											'<label for="hpsum-schedule-option" style="max-width: 500px;" rel="localize[hpsum.server.setSchedule]">Set Schedule</label>'+
										'<li></ol>'+
										'<div id="hpsum-schedule-details" ><table class="hp-column" style="margin-top:0px;">'+
										'<tbody>'+
										'<tr class="hp-column-item">'+
											'<td><label rel="localize[hpsum.node.masternodetime]">Master Node Time:</label></td>'+
											'<td><label style="margin-left: 10px;" id="hpsum-masternode-time"> </label></td>'+
										'</tr>'+
										'<tr class="hp-column-item">'+
											'<td><label rel="localize[hpsum.node.schedulefrom]">From:</label></td>'+
											'<td><input id="' + this.input_id1 + '" placeholder="Date + Time" readonly="true"></td>'+
											'<td><label style="display: inline-block;" class="hp-error" id="hpsum-schedule-from-error" rel="localize[hpsum.node.schedulefromerror]">Schedule From time should be 30 minutes later than system current time.</label></td>'+
										'</tr>'+
										'<tr class="hp-column-item">'+
											'<td><label rel="localize[hpsum.node.scheduleto]">To:</label></td>'+
											'<td><input id="' + this.input_id2 + '" placeholder="Date + Time" readonly="true"></td>'+
											'<td><label style="display: inline-block;" class="hp-error" id="hpsum-schedule-to-error" rel="localize[hpsum.node.scheduletoerror]">Schedule To time should be atleast 1 hour later than Schedule From time.</label></td>'+
										'</tr>'+
									'</tbody>'+
								'</table></div>';

						$(container ).html(html);
						
						
						$('#'+ this.input_id1 ,$(container)).hpsumDateTime();
						$('#'+ this.input_id2 ,$(container)).hpsumDateTime();

						$(RUN_NOW,$(container)).on('click',function()
							{
								_this.runNow();		
							}
						);

						$(SCHEDULE_OPTION, $(container)).on('click',function()
							{
								_this.scheduleoption();
							}
						);

			         	$('#'+ this.input_id1 ,$(container)).on('click',function()
							{
								
								if(this.input_id1 == undefined)
								{
									$('#'+ this.id,$(container)).removeClass("hp-error");
								}
								else
								{
									$('#'+ this.input_id1,$(container)).removeClass("hp-error");
								}
								
								$(SCHEUDLE_FROM_ERR,$(container)).hide();
								options.enableButton();
							}
						);
						
						$('#'+ this.input_id2 ,$(container)).on('click',function()
							{
								if(this.input_id2 == undefined)
								{
									$('#'+ this.id,$(container)).removeClass("hp-error");
								}
								else
								{
									$('#'+ this.input_id2,$(container)).removeClass("hp-error");
								}
								
								$(SCHEUDLE_TO_ERR,$(container)).hide();
								options.enableButton();
							}
						);
							
						$('#'+ this.input_id1,$(container)).on('keydown', function (e) {
							e.preventDefault();
						});
						
						$('#'+ this.input_id2,$(container)).on('keydown', function (e) {
							e.preventDefault();
						});
						
						 $('#'+ this.input_id1,$(container)).hide();
						 $('#'+ this.input_id2,$(container)).hide();
						 $(SCHEUDLE_FROM_ERR,$(container)).hide();
						 $(SCHEUDLE_TO_ERR,$(container)).hide();
						 $('#'+ this.input_id1,$(container)).removeClass("hp-error");		
						 $('#'+ this.input_id2,$(container)).removeClass("hp-error");		

        			};

        			this.selectImmediately = function(){
        				var container   = this.parentElement;
        				$(RUN_NOW,$(container)).trigger("click");

        			};

        			this.selectScheduled = function(){
        				var container   = this.parentElement;
        				$(SCHEDULE_OPTION, $(container)).trigger("click");

        			};

        			this.destroy = function()
        			{
						//Clear the timer
						if(_this.t)
         				{
         					clearTimeout(_this.t)
         					_this.t=null;
         				}
        				var container   = this.parentElement;
        				$(container).html("");
        			};

        			this.getScheduleDateTime = function(isfromtime)
        			{
						var container   = this.parentElement;
						if($(RUN_NOW,$(container)).is(":checked"))
							return "";        				
						if(isfromtime)
						{
							return $('#' + this.input_id1,$(this.parentElement)).val();
						}
						else
						{
							return $('#' + this.input_id2,$(this.parentElement)).val();
						}
        		 		
        
        			};
					
        			this.isScheduleSelected = function()
					{
        				var container = this.parentElement;
        				if($(SCHEDULE_OPTION, $(container)).is(":checked"))
        				{
        					return true;				/* user has clicked on Schedule Radio button */
        				}
        				else 
        				{
        					return false;				/* user has cliecked on Now radio button or Now radio button is auto checked */
        				}
        			}

        			this.validateUserEnteredTime = function()
					{
        				var container = this.parentElement;
						var isScheduleError = false, isFromtime = true;
						var scheduleFromDateTime = this.getScheduleDateTime(isFromtime);
						var scheduleToDateTime = this.getScheduleDateTime(!isFromtime);
						if(scheduleFromDateTime != "")
						{
							isScheduleError = this.validateScheduleDateTime(this.master_node_current_time, scheduleFromDateTime, isFromtime);
							if(scheduleToDateTime != "")
							{
								var isScheduleToError = this.validateScheduleDateTime(scheduleFromDateTime, scheduleToDateTime, !isFromtime);
								isScheduleError = isScheduleToError && isScheduleError;
							}
						}
						else
						{
							this.showorHideDateTimeError(isFromtime, !isScheduleError);
						}
						return isScheduleError;
        			};

        			this.setTimeinSchedulePlugin = function(masterNodeCurrentTime,scheduledTime){
         					this.master_node_current_time  = masterNodeCurrentTime;
							this.scheduled_date_time = scheduledTime;
         			};

         			this.setMasterNodeTimer = function(masterNodeCurrentTime)
         			{
         					var container  = _this.parentElement;
         					this.master_node_current_time = masterNodeCurrentTime;
							$('#hpsum-masternode-time',$(container)).text(this.master_node_current_time);
							
							//today = new Date('2015-08-20T11:54:00');
							//if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true ))
							//if not chrmore append T
							
							today = new Date(getBrowserDateString(this.master_node_current_time));
							startTime();
         			};

         			this.runNow=function()
         			{
         			    var container  = _this.parentElement;
         			    $(RUN_NOW,$(container)).attr('checked', true);
						$(SCHEDULE_OPTION,$(container)).attr('checked', false);
						$(SCHEDULE_DETAILS, $(container)).hide();
						options.enableButton();
         			};

         			this.scheduleoption = function(){
			         	var container  = _this.parentElement;
						$(RUN_NOW,$(container)).attr('checked', false);
						$(SCHEDULE_OPTION,$(container)).attr('checked', true);
						$(SCHEDULE_DETAILS, $(container)).show();
						$('#'+ this.input_id1,$(container)).show();
						$('#'+ this.input_id2,$(container)).show();
//						var minDate = getDate(_this.master_node_current_time);
						
			        };

			        this.validateScheduleDateTime=function(comparetime, scheduleDateTime, isFromtime)
			        {
						var ScheduleTime = new Date(getBrowserDateString(scheduleDateTime)).getTime();
						var MasterTime = new Date(getBrowserDateString(comparetime)).getTime();
         				var diffTimeinMins = (ScheduleTime - MasterTime)/1000/60;
						var timediff = 29;
						if(!isFromtime)
						{
							timediff = 59;
						}
						if(diffTimeinMins >  timediff)
         				{
							this.showorHideDateTimeError(isFromtime, false);
							return true;
         				}
						else
						{
							this.showorHideDateTimeError(isFromtime, true);
							options.disableButton();
							return false;
						}
         			};
					
					this.showorHideDateTimeError=function(isFromtime,showerror)
					{
						var container  = _this.parentElement;
						if(isFromtime)
						{
							if(showerror)
							{
								$(SCHEUDLE_FROM_ERR,$(container)).show();
								$('#' + this.input_id1,$(container)).addClass("hp-error");
							}
							else
							{
								$( SCHEUDLE_FROM_ERR , $(container)).hide();
								$( '#' + this.input_id1 , $(container)).removeClass("hp-error");
							}
							
						}
						else
						{
							if(showerror)
							{
								$(SCHEUDLE_TO_ERR,$(container)).show();
								$('#' + this.input_id2,$(container)).addClass("hp-error");
							}
							else
							{
								$( SCHEUDLE_TO_ERR , $(container)).hide();
								$( '#' + this.input_id2 , $(container)).removeClass("hp-error");
							}
							
						}
					}
         			function startTime() 
         			{
         				var container  = _this.parentElement;
         				if(_this.t)
         				{
         					//We have to clean the old timer.
         					clearTimeout(_this.t)
         					_this.t=null;
         				}
					    today.setSeconds(today.getSeconds()+1);
					    var y= Number(today.getFullYear());
					    var month = Number(today.getMonth())+1;
					    var date = today.getDate();
					    var h=today.getHours();
					    var m=today.getMinutes();
					    var s=today.getSeconds()+1;
						var day = days[today.getDay()];
						month = twoDigitNumber(month);
						date = twoDigitNumber(date);
					    m = twoDigitNumber(m);
					    s = twoDigitNumber(s);
						if (s == 60)
						{
							s= twoDigitNumber(0);
							m=m+1;
							if (m == 60)
							{
								m = twoDigitNumber(0);
								h = h+1;
							}
						}
						_this.master_node_current_time = month+"-"+date+"-"+y+" "+h+":"+m+":"+s;
					    $(MASTER_NODE_TIME,$(container)).text(_this.master_node_current_time);
					    _this.t = setTimeout(function(){startTime()},1000);
						    
					}

					function twoDigitNumber(i) 
					{
		    			if (i<10)   // add zero in front of numbers < 10
		    			 {
		    			   i = "0" + i 
		    			 } 
		    			return i;
					}

					function uuid()
					{
						
						return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    					var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    						return v.toString(16);
						});
					}

					function getDate(stringDate)
					{
						//yy-mm-dd HH:mm
						var regex=/(.*)-(.*)-(.*) (.*):(.*)/g;
					    var match = regex.exec(stringDate);
					    if(match != null)
					    {
					    	var y= Number(match[1]);
					    	var month = Number(match[2])-1;
					    	var date = Number(match[3]);
					    	var h=Number(match[4]);
					    	var m=Number(match[5]);

					    	return new Date(y,month,date,h,m,0);
					    }
					    return null;
					}

					function getBrowserDateString(dateString)
					{
						 if(navigator.userAgent.indexOf("Chrome") == -1)
						 {
							var timeInMasterNode = dateString.split(' ');
							if(navigator.userAgent.indexOf("Firefox") != -1)
							{
								var date = timeInMasterNode[0].replace(/-/g, ' ');
								return (date+' '+timeInMasterNode[1]);
							}
							else
							{
								return (timeInMasterNode[0]+'T'+timeInMasterNode[1]);
							}
						 }
						 else
						 {
						 	return dateString;
						 }
					}


        			this.init();
        		}
         

		 // Plugin initialization code

         var scheduleInstance = null;
         if (typeof options === "string") {
                //To call the plugin functions after initialization.
                var args = Array.prototype.slice.call(arguments, 1);

                if(!this[0])
                	return;
              
                //assuming jquery object is returned
                scheduleInstance = $.data(this[0], '_hpsumSchedule');
                //Lets try to get the data from the element
                if (!scheduleInstance) {
                        log.error("This object has not yet been initialized to use Schedule Plugin");
                        return;
                    } else if (!$.isFunction(scheduleInstance[options]) || options.charAt(0) === '_') {
                        log.error("No function by name " + options + ' exist in Schedule Plugin');
                        return;
                    }
                    // call method
                if(options == "destroy")
                {
                	scheduleInstance.destroy();
                	$.removeData(this[0],'_hpsumSchedule');
                	scheduleInstance = null;
                	return
                }

                return scheduleInstance[options].apply(scheduleInstance, args);
                
            } else {
                //Request for a new initialization
                return this.each(function() {
                    scheduleInstance = $.data(this, '_hpsumSchedule')
                    if (!scheduleInstance) {
                        scheduleInstance = new SchedulePlugin(this, options);
                        $.data(this, '_hpsumSchedule', scheduleInstance);
                    }
                });
            }
        }

    }(jQuery));
});
