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

define(['hpsum/presenter/node/NodePresenter',
    'hp/core/Router',
    'hp/view/FormStateView',
	'hp/view/DialogView',
    'hp/core/HelpMenu',
    'hp/core/Localizer',
	'text!hpsumpages/node/delete_confirm.html',
    'text!hpPages/core/header_help.html',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'hp/lib/jquery.hpToggle',
    'lib/jquery.selectBox',
	'hp/lib/jquery.hpPanels'],
function(presenter, router, FormStateView, DialogView,  helpMenu, localizer,deleteConfirmHtml, headerHelpHtml) { "use strict";
    	
    	var ScheduleShowView = (function() {
    		var	FORM = '#hpsum-node-schedule-form',
    			RESET = '#hpsum-node-reset',
    			FREQPANELS = '#hpsum-nodes-frequency-panels',
    			PANELS ='#hpsum-nodes-schedule-details-panels',
    			DAILYPANEL ='#hpsum-node-schedule-daily-panel',
    			WEEKLYPANEL ='#hpsum-node-schedule-weekly-panel',
    			MONTHLYPANEL ='#hpsum-node-schedule-monthly-panel',
    			DAILYRECUR ='#hpsum-node-schedule-recur-daily',
    			WEEKLYRECUR ='#hpsum-node-schedule-recur-weekly',
    			MONTHLYRECUR ='#hpsum-node-schedule-recur-monthly',
    			DATETIMESECTION ='#hpsum-node-schedule-datetimepick',
    			SCHEDULETOGGLE ='#hpsum-node-schedule-enable',
    			FREQOPTION ='#hpsum-node-schedule-frequency',
            	ROUTE_PREFIX = '/node/schedule',
           		SCHEDULE = '#hpsum-node-schedule',
				SCHEDULE_DATE = '#hpsum-node-schedule-date',
				SCHEDULE_TIME = '#hpsum-node-schedule-time',
				SCHEDULE_DELETE = '#hpsum-node-schedule-delete',
				DELETE_TITLE = '#hpsum-nodes-delete-title',
				SCHEDULE_ERROR = '#hpsum-node-schedule-error';
				
    	function ScheduleShowView(){
    			
			var scheduled_date_time = '';
			var nodeItem=null;
			var action;
          
            function reset() {
				if($(SCHEDULETOGGLE).attr('checked') === "checked"){
					$(SCHEDULETOGGLE).click();	
					$(SCHEDULETOGGLE).removeAttr("checked");
				}
                $(SCHEDULE_DATE).val("");
				$(SCHEDULE_TIME).val(' ');
            }
            
            function resetCancel() {
                reset();
            }
			function onItemChange(item) {
			    nodeItem = item.hapi;
				var scheduled_date_time_old;
				var scheduled_time;
				var scheduled_date;
				var scheduled_time_hrs_mins;
				var scheduled_time_hrs;
				var scheduled_time_mins;
				
				$(SCHEDULE_ERROR).hide();
				if(nodeItem)
				{
					scheduled_date_time = nodeItem.schedule_date_time;
					if(nodeItem.scheduled === "false")
					{
						$('#hpsum-node-schedule-delete').hide();
						if($(SCHEDULETOGGLE).attr('checked') === "checked"){
							$(SCHEDULETOGGLE).click();	
							$(SCHEDULETOGGLE).removeAttr("checked");
						}
					}
					else if(nodeItem.scheduled === "true")
					{
						$('#hpsum-node-schedule-delete').addClass('hp-primary').show();
						if($(SCHEDULETOGGLE).attr('checked') === undefined){
							$(SCHEDULETOGGLE).click();	
							$(SCHEDULETOGGLE).attr("checked","checked");
						}
					}
					if(scheduled_date_time === "")
					{
						$(SCHEDULE_DATE).val(' ');
						$(SCHEDULE_TIME).val(' ');
					}	
					else
					{	
						scheduled_date_time_old = scheduled_date_time.split(' ');
						scheduled_date = scheduled_date_time_old[0];
						$(SCHEDULE_DATE).val(scheduled_date);
						
						scheduled_time = scheduled_date_time_old[1];
						scheduled_time_hrs_mins = scheduled_time.split(':');
						scheduled_time_hrs = scheduled_time_hrs_mins[0];
						scheduled_time_mins = scheduled_time_hrs_mins[1];
						
						var scheduled_time_hrs_new;
						var scheduled_time_new;						
						
						if (scheduled_date_time_old[2] == 'PM')
						{
							if (scheduled_time_hrs < 12)
							{
								scheduled_time_hrs_new = parseInt(scheduled_time_hrs) + 12;	
								scheduled_time_new = scheduled_time_hrs_new + ':' + scheduled_time_mins;
							}
							else if ( scheduled_time_hrs == 12)
							{
								scheduled_time_hrs_new = parseInt(scheduled_time_hrs) + 0;	
								scheduled_time_new = scheduled_time_hrs_new + ':' + scheduled_time_mins;
							}
						}
						else if ( scheduled_date_time_old[2] == 'AM')
						{
							if ( scheduled_time_hrs == 12)
							{
								scheduled_time_hrs_new = parseInt(scheduled_time_hrs) - 12;
								scheduled_time_new = '0' + scheduled_time_hrs_new + ':' + scheduled_time_mins;
							}
							else if ( scheduled_time_hrs < 12)
							{
								if ( scheduled_time_hrs < 10 )
								{
									scheduled_time_hrs_new = parseInt(scheduled_time_hrs) + 0;
									scheduled_time_new = '0' + scheduled_time_hrs_new + ':' + scheduled_time_mins;
								}
								else
								{
									scheduled_time_hrs_new = parseInt(scheduled_time_hrs) + 0;
									scheduled_time_new = scheduled_time_hrs_new + ':' + scheduled_time_mins;
								}
							}
						}
						$(SCHEDULE_TIME).val(scheduled_time_new);
					}
				}
			}
				
			function btnScheduleDelete()
			{
				var scheduled;
				
				if($(SCHEDULETOGGLE).attr('checked') === "checked")
					scheduled = 'yes';
				else
					scheduled = 'no';
				
				if( scheduled === 'yes')
				{		
					var schedule_information;
					var node_id = nodeItem.node_id;
					action = 'delete';
						 
					presenter.ScheduleNodes(node_id,action,scheduled,schedule_information, {
						success : function(data) {
							onScheduleNodesSuccess(data); 
						},
						error : function(errorInfo) {
							onScheduleNodesError(errorInfo);
						}
					});	
				}
			}
			
			function  btnScheduleClicked()
			{
				var scheduled;
				var node_id = nodeItem.node_id;
				var date = "";
				var time = "";

				if($(SCHEDULETOGGLE).attr('checked') === "checked")
					scheduled = 'yes';
				else
					scheduled = 'no';
				
				if(scheduled_date_time == "")
					action = 'create';
				else
					action = 'update';

				if(scheduled === "yes")
				{
					date = $(SCHEDULE_DATE).val();
					time = $(SCHEDULE_TIME).val();
					var date_parse = date.split('-');
					var date_parse_str = date_parse[2] + '/' + date_parse[1] + '/' + date_parse[0];
					var time_parse = time.split(':');
					var time_hrs = time_parse[0];
					var time_mins = time_parse[1];
					if(time_hrs >= 12)
					{
						if(time_hrs == 12)
							time = time_hrs + ':' + time_mins + ' ' +'PM';
						else
						{
							var time_hrs_old = time_hrs - 12 ;
							if((time_hrs_old) <= 9)
							time = '0' + time_hrs_old + ':' + time_mins + ' ' +'PM';
							else 
							time = time_hrs_old + ':' + time_mins + ' ' +'PM';
						}
					}
					else if (time_hrs == 0)
					{
						time = (parseInt(time_hrs) + 12) + ':' + time_mins + ' ' +'AM';
					}
					else if (time_hrs < 12)
					{
						time = time_hrs + ':' + time_mins + ' ' +'AM';
					}
				}

				var schedule_information = {date:date, time:time};

				presenter.ScheduleNodes(node_id,action,scheduled,schedule_information, {
					success : function(data) {
						onScheduleNodesSuccess(data); 
					},
					error : function(errorInfo) {
							onScheduleNodesError(errorInfo);
						}
				});
			}

			function onSchedDeleteSuccess()
			{
			}
			function onSchedDeleteError()
			{
			
			}
			function onScheduleNodesError(errorInfo)
			{
				$(SCHEDULE_ERROR).show();
				$(SCHEDULE_ERROR).html(errorInfo);
				$(SCHEDULETOGGLE).bind('change', function(){
					$(SCHEDULE_ERROR).hide();
				});
				$(SCHEDULE_DATE).bind('change', function(){
					$(SCHEDULE_ERROR).hide();
				});
				$(SCHEDULE_TIME).bind('change', function(){
					$(SCHEDULE_ERROR).hide();
				});
			}
			
			function onScheduleNodesSuccess(data)
		    {
				if((action === "create") || (action === "update"))
					presenter.deploy(nodeItem, {
						success : onDeploySuccess,
						error : onDeployError
					});
					
				router.go('/node/show');
			}
            
			function onDeploySuccess()
			{
			}
			function onDeployError()
			{			
			}
			
            function toggleSchedule(cb)
            {
            	if(cb.target.checked){
            		$(DATETIMESECTION).show();
            		//$('input[name="hpsum-node-schedule-frequency"]').attr('disabled',false);
            		//showFrequencyPanels($("input[name='hpsum-node-schedule-frequency']:checked").val());
            	}
            	else{
            		$(DATETIMESECTION).hide();
            		$('input[name="hpsum-node-schedule-frequency"]').attr('disabled',true);
            		$(DAILYPANEL).hide();
            		$(WEEKLYPANEL).hide();
    				$(MONTHLYPANEL).hide();
            	}
            }
           
            function showFrequencyPanels(value) {
            	if(value.target)
            		value = value.target.value;
            	if(value == "daily"){
            		$(DAILYPANEL).show();
            		$(WEEKLYPANEL).hide();
    				$(MONTHLYPANEL).hide();
    				// $(PANELS).hpStackedPanels('setFirstPanel');
            	}
            	else if(value == "weekly"){
            		$(DAILYPANEL).hide();
            		$(WEEKLYPANEL).show();
    				$(MONTHLYPANEL).hide();
            	}
            	else if(value == "monthly"){
            		$(DAILYPANEL).hide();
            		$(WEEKLYPANEL).hide();
    				$(MONTHLYPANEL).show();
            	}
            }
					
    		this.init = function() {

    			$(DATETIMESECTION).hide(); 
    			$('input[name="hpsum-node-schedule-frequency"]').attr('disabled','disabled');
    			//$('input[name="hpsum-node-schedule-frequency"]').click(showFrequencyPanels);
    			$(DAILYPANEL).hide();
    			$(WEEKLYPANEL).hide();
    			$(MONTHLYPANEL).hide();
    			$(FREQPANELS).hpPanels();
    			$(SCHEDULETOGGLE).hpToggle({checked: 'On', unchecked: 'Off'});
    			$(SCHEDULETOGGLE).bind('change',toggleSchedule);           

		// 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);
                }

                $(RESET).click(function() {
                    reset();
                });
				
				$('#hpsum-node-schedule-delete').click(function () {
				
					var contents = $(deleteConfirmHtml);
					$('#hpsum-delete-node',contents).html(localizer.getString('hpsum.common.continueWithDelete')); // Add in translation
					$('#hpsum-node-delete-cancel',contents).show();
					
					localizer.localizeDom(contents);
					var dialogView = new DialogView();
					dialogView.init({contents: contents,
						ok: function () {
							btnScheduleDelete();
						},
						cancel: function () {
							router.go('/node/show');
						}
					});
                });

				$('#hpsum-node-schedule').click(function () {
				    btnScheduleClicked();
                    //router.go('/node/show/');
					
                });
                
                $(PANELS).hpStackedPanels({
                    	//panelSelector : PANEL_SELECTOR
                	});
                
                this.resume();
            };
            
            this.resume = function () {
				presenter.on('itemChange', onItemChange);
            	$(FREQPANELS).hpPanels('reset');
            };
            
            this.pause = function () {
			presenter.off('itemChange', onItemChange);
            };
    		
    	}	
    	return ScheduleShowView;
    }());
    	
    return new ScheduleShowView();	
    		
    });

