// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (OneTouchUpdateAdvOptionsView)
 * This is a view class for One Touch Update Advanced options.
 */
define(['hp/core/Router',
    'hp/core/Notifications',
	'hp/core/HelpMenu',
	'hp/services/REST',
    'hp/model/Session',
    'hp/core/Localizer',
	'hpsum/presenter/node/NodePresenter',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'hp/lib/jquery.hpPanels',
    'lib/jquery.selectBox',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpToggle',
	'hp/lib/jquery.hpSearchCombo'],
function(router, notifications, helpMenu, REST, session, localizer, nodepresenter) { "use strict";

    var OneTouchUpdateAdvOptionsView = (function() {
      
        var OK = '#hpsum-otu-advoptions-ok',
            CANCEL = '#hpsum-otu-advoptions-close',
			PANEL_SELECTOR = '#hpsum-advoptions-panel-selector',
            PANELS = '#hpsum-otu-advoptions-panels',
			INSTALLATIONOPTION = '#hpsum-installation-option',
			INSTALL_ERROR='#force-options-tbody-err',
			FIRMWARECHKBOXCOMP ='.firmwarechkbox',
			SOFTWARECHKBOXCOMP ='.softwarechkbox',
			DAILYPANEL ='#hpsum-otu-schedule-daily-panel',
			WEEKLYPANEL ='#hpsum-otu-schedule-weekly-panel',
			MONTHLYPANEL ='#hpsum-otu-schedule-monthly-panel',
			DAILYRECUR ='#hpsum-otu-schedule-recur-daily',
			WEEKLYRECUR ='#hpsum-otu-schedule-recur-weekly',
			MONTHLYRECUR ='#hpsum-otu-schedule-recur-monthly',
			DATETIMESECTION ='#hpsum-otu-schedule-datetimepick',
			SCHEDULETOGGLE ='#hpsum-otu-schedule-enable',
			FREQOPTION ="hpsum-otu-schedule-frequency",
            ROUTE_PREFIX = '/guided-update/advoptions',
			COMPVERBOSEOPTION = '#hpsum-comp-verbose-checkbox',
			CLEANUP_ONEXIT_OPTIONS = '#hpsum-advopt-cleanup-onexit-checkbox',
			CLEANUP_ONEXIT_OPTIONS_LABEL = '#hpsum-advopt-cleanup-onexit-label',
            REBOOTDELAY = '#hpsum-reboot-delay',
            REBOOTDELAYERR = '#hpsum-reboot-delay-error-label',
			REBOOT_DELAY_SEC = '60',
			REBOOTMSG = '#reboot-message',
			REBOOTOPTIONS = '#hpsum-otu-advoptions-reboot';
            var OTU_INSTALLATION_OPTIONS_TITLE = '#hpsum-downgrade-rewrite-text';
            var OTU_INSTALLATION_OPTIONS_CONTENT = '#hpsum-common-install-options';
            
        /**
         * Constructor
         */
        function OneTouchUpdateAdvOptionsView() {
          
            var addInProgress = false, 
				nodes = [];
          
            function onItemAddSuccess(item) {
                addInProgress = false;
            }

            /**
             * @private
             */
            function onItemAddError(errorMessage) {
                notifications.show(errorMessage, 'error');
                addInProgress = false;
                $(CANCEL).trigger('click');
            }

            /**
             * @private
             * loadNodeAttributes - Call node's getattributes command to get force options, reboot options etc
             */
            function loadNodeAttributes()
            {
	        //Below Code is commented to use Node API instead of Session API.
            	/*
            	REST.getURI("Session/" + session.getToken() + "/getattributes", {
                    			success : function(data) {
                        			ongetAttributesSuccess(data);
                    		 	},
                    			error : function(errorInfo) {
                        			ongetAttributesError(errorInfo);
                    			}
                			});
				*/
				if(nodes.length <= 0)
					return;
				nodepresenter.otheroption(nodes[0],  {
                    			success : function(data) {
                        			ongetAttributesSuccess(data);
                    		 	},
                    			error : function(errorInfo) {
                        			ongetAttributesError(errorInfo);
                    			}
                			});
            }

            function getNodeDataForBaseline()
            {
                if (nodes.length <= 0)
                    return;
                var nodeItem = { node_id: nodes[0].node_id }
                nodepresenter.getNodeData(nodeItem, {
                    success: function (data) {
                        //if baseline is installset hide the force options.
                        var baselineList = data.hapi.baselines;
                        if (baselineList.length > 0 && baselineList[0].indexOf('/') == -1) {
                            //its an installset. 
                            $(OTU_INSTALLATION_OPTIONS_TITLE).hide();
                            $(OTU_INSTALLATION_OPTIONS_CONTENT).hide();
                        }
                        else {
                            $(OTU_INSTALLATION_OPTIONS_TITLE).show();
                            $(OTU_INSTALLATION_OPTIONS_CONTENT).show();
                        }
                    },
                    error: function ()
                    { }
                });
            }
            
            function ongetAttributesSuccess(data){
				var guimode = session.getProperty("gui_mode");
				if (guimode === "offline_automatic" || guimode === "offline_interactive") {
					$("#hpsum-installation-option option[value='upgradeSoftware']").remove();
					$("#hpsum-installation-option option[value='software']").remove();
					$("#hpsum-installation-option option[value='rewriteSoftware']").remove();
					$("#hpsum-installation-option option[value='downgradeSoftware']").remove();
					$("#hpsum-installation-option option[value='upgradeBoth']").remove();
					$("#hpsum-installation-option option[value='both']").remove();
					$("#hpsum-installation-option option[value='rewriteBoth']").remove();
					$("#hpsum-installation-option option[value='downgradeBoth']").remove();
				}
				
				var rewriteOption = data.hapi.installation_option.rewrite;
				var downgradeOption = data.hapi.installation_option.downgrade;
				var firmwareOption = data.hapi.installation_option.firmware;
				var softwareOption = data.hapi.installation_option.software;
				
				if ( !rewriteOption  && !downgradeOption )
				{
					if(firmwareOption && softwareOption){
						$(INSTALLATIONOPTION).val('upgradeBoth');
					}
					else if(firmwareOption){
						$(INSTALLATIONOPTION).val('upgradeFirmware');
					}
					else if(softwareOption){
						$(INSTALLATIONOPTION).val('upgradeSoftware');
					}
				}
				else if ( rewriteOption  && downgradeOption )
				{
					if(firmwareOption && softwareOption)
						$(INSTALLATIONOPTION).val('both');
					else if(firmwareOption)
						$(INSTALLATIONOPTION).val('firmware');
					else if(softwareOption)
						$(INSTALLATIONOPTION).val('software');
				}
				else if ( rewriteOption )
				{
					if(firmwareOption && softwareOption)
						$(INSTALLATIONOPTION).val('rewriteBoth');
					else if(firmwareOption)
						$(INSTALLATIONOPTION).val('rewriteFirmware');
					else if(softwareOption)
						$(INSTALLATIONOPTION).val('rewriteSoftware');
				}
				else if ( downgradeOption )
				{
					if(firmwareOption && softwareOption)
						$(INSTALLATIONOPTION).val('downgradeBoth');
					else if(firmwareOption)
						$(INSTALLATIONOPTION).val('downgradeFirmware');
					else if(softwareOption)
						$(INSTALLATIONOPTION).val('downgradeSoftware');

				}
					
				if(!data.hapi.type.match(/windows/i)) {
					$("#hpsum-comp-verbose-descr").hide();
					$(COMPVERBOSEOPTION).hide();
				}
				else if(data.hapi.verbose == true)
				{
					$(COMPVERBOSEOPTION).prop("checked", true);
				}
					
				$(INSTALLATIONOPTION).selectBox('reset');

				var rebootopt = data.hapi.reboot_options.action;
				if (guimode === "offline_automatic" || guimode === "offline_interactive") {
					$(".hpsum-otu-advoptions-disable").find('input,textarea,select,button').prop("disabled", true);
					$(REBOOTDELAY).val("1");
				}
				else if (rebootopt == "Never") {
					$(".hpsum-otu-advoptions-disable").find('input,textarea,select,button').prop("disabled", true);
					$(REBOOTDELAY).val('');
				} else { 
					$(REBOOTDELAY).val(data.hapi.reboot_options.delay/60);
					$(REBOOTMSG).val(data.hapi.reboot_options.message);
					$(".hpsum-otu-advoptions-disable").find('input,textarea,select,button').prop("disabled", false);
				}
				
				$('#reboot-options').selectBox('value', rebootopt);
			}
			
			function ongetAttributesError(error){
				
			}

            function validateRebootDelay() {
			var rebootopt = $('#reboot-options option:selected').val();
			var delayMinutes = $(REBOOTDELAY).val();
			var valid = true;
			// TODO: Enforce a time range on the reboot delay?
            // Check to see if it appears to be a number.
			
			var guimode = session.getProperty("gui_mode");
			if (guimode === "offline_automatic" || guimode === "offline_interactive") {
				delayMinutes = "1";
			}
			if (rebootopt != "Never") {
				if((isNaN(delayMinutes) && !isFinite(delayMinutes)) || 
				   (delayMinutes < 1 || delayMinutes > 60)){
						$(REBOOTDELAY).addClass("hp-error");
						$(REBOOTDELAYERR).text(localizer.getString("hpsum.node.rebootDelaySecondsErrMsg"));
						$(REBOOTDELAYERR).show();
						valid = false;       
                } 
				else {
					$(REBOOTDELAY).val(parseInt(delayMinutes));
					$(REBOOTDELAY).removeClass("hp-error");
					$(REBOOTDELAYERR).hide();
				}
			}
			return valid;
            }

            function validate() {
                return validateRebootDelay();
            }

			/**
            * @private
            * onCancel - Call session's resetattributes command.
            */
			function onCancel(){
			   reset();
			}
			
			function errormsg()
			{
				$(INSTALL_ERROR).hide();
			}
			
            /**
             * @private
             * onOk - Call session's setattributes command to save force options, reboot options etc
             */
            function onOk() {

                if (!validate()) {
                    return false;
                }
					
            	var bforceopt = true;
				var installation_rewrite = false;
				var installation_downgrade = false;
				var installation_firmware = false;
				var installation_software = false;
                var type = $(INSTALLATIONOPTION).val();
				var bVerbose = false, bCleanup_onexit = false;
				
				if ( type == "upgradeBoth"){
					installation_software = true;
					installation_firmware = true;
					bforceopt = false;
				}
				else if ( type == "upgradeFirmware"){
					installation_firmware = true;
					bforceopt = false;
				}
				else if ( type == "upgradeSoftware"){
					installation_software = true;
					bforceopt = false;
				}
				else if ( type == "downgradeFirmware"){
					installation_downgrade = true;
					installation_firmware = true;
				}
				else if ( type == "downgradeSoftware"){
					installation_downgrade = true;
					installation_software = true;
				}
				else if ( type == "downgradeBoth"){
					installation_downgrade = true;
					installation_firmware = true;
					installation_software = true;
				}
				else if ( type == "rewriteFirmware"){
					installation_rewrite = true;
					installation_firmware = true;
				}
				else if ( type == "rewriteSoftware"){
					installation_rewrite = true;
					installation_software = true;
				}
				else if ( type == "rewriteBoth"){
					installation_rewrite = true;
					installation_firmware = true;
					installation_software = true;
				}
				else if ( type == "firmware"){
					installation_downgrade = true;
					installation_rewrite = true;
					installation_firmware = true;
				}
				else if ( type == "software"){
					installation_downgrade = true;
					installation_rewrite = true;
					installation_software = true;
				}
				else if ( type == "both"){
					installation_downgrade = true;
					installation_rewrite = true;
					installation_firmware = true;
					installation_software = true;
				}
				
				if($(COMPVERBOSEOPTION).is(':checked'))
				{
					bVerbose = true;
				}
				
				if($(CLEANUP_ONEXIT_OPTIONS).is(':checked')) {
					bCleanup_onexit = true;
				}
				else {
					bCleanup_onexit = false;
				}
				
            	var rebootopt = $('#reboot-options option:selected').val();
				/* if(rebootopt == localizer.getString("hpsum.oneTouchUpdate.never")){
					rebootopt = "Never";
				}
				else if(rebootopt == localizer.getString("hpsum.common.ifNeeded")){
					rebootopt = "If needed";
				}
				else if(rebootopt == localizer.getString("hpsum.common.always")){
					rebootopt = "Always";
				}*/
								
            	var rebootdelay = $(REBOOTDELAY).val() * 60;
            	var rebootmsg = $(REBOOTMSG).val();         	
            	
            	var attributes = {
								 	hapi:
								 	{
												verbose: bVerbose,
												cleanup_onexit: bCleanup_onexit,
												cleanupall_onexit: false,
												reboot_options :
												{
										    		  delay: rebootdelay,
											          action: rebootopt,
											          message: rebootmsg
												},
												installation_option :
												{
													downgrade: installation_downgrade,
													rewrite: installation_rewrite,
													force: bforceopt,
													software : installation_software,
													firmware : installation_firmware
												}
									 }
				  };
			        //Below Code is commented to use Node API instead of Session API.
				/*
				REST.postObject("Session/" + session.getToken() + "/setattributes", 
								attributes,  "", 
            		         {
                    			success : function(data) {
                        			onSetAttributesSuccess(data);
                        			window.bRefreshReview = true;
                    		 	},
                    			error : function(errorInfo) {
                        			onSetAttributesError(errorInfo);
                    			}
                			}, {});
				*/
				var initialGetattr = null;
				nodepresenter.otheroption(nodes[0], {
				   success : function(data) {
				        initialGetattr = data;
						if(nodes.length > 0) {
					//send the setattribute command to engine
					if(initialGetattr.hapi.installation_option.downgrade != attributes.hapi.installation_option.downgrade ||
						initialGetattr.hapi.installation_option.rewrite != attributes.hapi.installation_option.rewrite ||
						initialGetattr.hapi.installation_option.software != attributes.hapi.installation_option.software ||
						initialGetattr.hapi.installation_option.firmware != attributes.hapi.installation_option.firmware ||
						initialGetattr.hapi.reboot_options.action != attributes.hapi.reboot_options.action ||
						initialGetattr.hapi.reboot_options.delay != attributes.hapi.reboot_options.delay ||
						($(COMPVERBOSEOPTION).is(':checked')) || 
						initialGetattr.hapi.reboot_options.message != attributes.hapi.reboot_options.message) {
					
						nodepresenter.setattribute(nodes[0], attributes, {
										success : function(data) {
											onSetAttributesSuccess(data);
											window.bRefreshReview = true;
					$(CANCEL).trigger('click');
										},
										error : function(errorInfo) {
											onSetAttributesError(errorInfo);
										}
									});
								}
					else{
							$(CANCEL).trigger('click');			
						}
				}
				
				return true;
				   },
				     error : function(errorInfo) {
					 }
				   });

			}
			
			function onSetAttributesSuccess(data){
				
			}
			
			function onSetAttributesError(error){
				
			}
			
			function changeLocation(location) {
                if (location.length > ROUTE_PREFIX.length) {
                    $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
                } else {
                    $(PANELS).hpStackedPanels('setFirstPanel');
                }
            }
            
			function toggleSchedule(cb)
            {
            	if(cb.target.checked){
            		$(DATETIMESECTION).show();
            		$('input[name="hpsum-otu-schedule-frequency"]').attr('disabled',false);
            		showFrequencyPanels($("input[name='hpsum-otu-schedule-frequency']:checked").val());
            	}
            	else{
            		$(DATETIMESECTION).hide();
            		$('input[name="hpsum-otu-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();
            	}
            }
			function loadNodes() {
				//get nodes from one touch update wizard page
				nodes = nodepresenter.getNodesForAdvOptions();
			}
          
            /**
             * @public
             */
            this.resume = function () {
				var guimode = session.getProperty("gui_mode");
				if (guimode === "offline_automatic") {
					$(REBOOTOPTIONS).hide();
					$(CLEANUP_ONEXIT_OPTIONS).hide();
					$(CLEANUP_ONEXIT_OPTIONS_LABEL).hide();
				}
				$(REBOOTDELAY).removeClass("hp-error");
                $(REBOOTDELAYERR).hide();
				if($('#reboot-options').val().toLowerCase() == "never"){
					$(REBOOTDELAY).attr("disabled", true);
					$(REBOOTMSG).attr("disabled", true);
				}
				else{
					$(REBOOTDELAY).attr("disabled", false);
					$(REBOOTMSG).attr("disabled", false);
				}
				$('#hpsum-node-delay-err-msg').hide(); 
				loadNodes();
				loadNodeAttributes();
				getNodeDataForBaseline();
            	window.bRefreshReview = false;
            };
            
            this.pause = function () {
            };
			
			function reset() {
				
				$("#reboot-options").val(localizer.getString("hpsum.oneTouchUpdate.never"));
				$(REBOOTDELAY).val(REBOOT_DELAY_SEC/60);
				$(REBOOTMSG).val(localizer.getString("hpsum.node.rebootMessage"));
				$(COMPVERBOSEOPTION).attr('checked', false);
				$(CLEANUP_ONEXIT_OPTIONS).attr('checked', false);
			}
            
            /**
             * @public
             * Initialization funtion for the object
             * All the controls actions are initialized in this function.
             */
            this.init = function() {
                
                //hide schedule option as it is yet to integrate
                $("#hpsum-otu-advoptions-schedule").hide();
		loadNodes();
                loadNodeAttributes();
                //get node data to get baseline details...
                getNodeDataForBaseline();


                $(OK).live('click', function(ev) {
                    onOk.call(this);
                    ev.preventDefault();
                });
				
				$(CANCEL).live('click', function(ev) {
					onCancel.call(this);
					ev.preventDefault();
                });
				$('#hpsum-downgrade-rewrite-text').html(localizer.getString("hpsum.node.installationOptions.message"));
				$('#hpsum-downgrade-rewrite-text').removeClass('hp-collapsed');
				
				$(INSTALLATIONOPTION).selectBox({autoWidth: false});
				$("#reboot-options").selectBox({autoWidth: false});
				$(INSTALLATIONOPTION).val('None');
				$('#hp-install-firmware-software').hide();
				$(INSTALL_ERROR).hide();
				
				//By Default reboot-options value is Never so disable the Reboot delay and Reboot message.
				$(".hpsum-otu-advoptions-disable").find('input,textarea,select,button').prop("disabled", true);
				
				$("#reboot-options").change(function() {
					var type = $('#reboot-options option:selected').val();
					var guimode = session.getProperty("gui_mode");
					if (type == "Never" || guimode === "offline_automatic" || guimode === "offline_interactive") {
					$(".hpsum-otu-advoptions-disable").find('input,textarea,select,button').prop("disabled", true);
					$(REBOOTDELAY).val('');
					$(REBOOTDELAY).removeClass("hp-error");
					$(REBOOTDELAYERR).hide();
					}
					else
					{
					$(".hpsum-otu-advoptions-disable").find('input,textarea,select,button').prop("disabled", false);
					}
				});
				
				$(REBOOTDELAY).unbind('keyup').bind('keyup', function(){
					$(REBOOTDELAYERR).hide();
					$(REBOOTDELAY).removeClass('hp-error');
					validateRebootDelay();
				}); 
				
				$(REBOOTDELAY).bind('change', function(){
					$(REBOOTDELAYERR).hide();
					$(REBOOTDELAY).removeClass('hp-error');
				}); 
				
				$(PANELS).hpStackedPanels({
                    panelSelector : PANEL_SELECTOR
                });

				$(REBOOTDELAYERR).hide();
				$(DATETIMESECTION).hide(); 
    			$('input[name="hpsum-otu-schedule-frequency"]').attr('disabled','disabled');
    			$('input[name="hpsum-otu-schedule-frequency"]').click(showFrequencyPanels);
    			$(DAILYPANEL).hide();
    			$(WEEKLYPANEL).hide();
    			$(MONTHLYPANEL).hide();
    			$(SCHEDULETOGGLE).hpToggle({checked: 'On', unchecked: 'Off'});
    			$(SCHEDULETOGGLE).bind('change',toggleSchedule); 
				
				
				router.watch('one-touch-update advoptions section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
					
                this.resume();
            };
        }

        return OneTouchUpdateAdvOptionsView;
    }());
    
    return new OneTouchUpdateAdvOptionsView();
});
