// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (DeployDomainView)
 * This is a view class for Integrity iLO deploy domain screen.
 */
define(['hpsum/presenter/node/NodePresenter',
	'hp/core/Router',
	'hp/core/UrlFragment',
	'hp/core/Notifications',
	'hp/core/Localizer',
	'hp/model/Session',
	'hp/services/REST',
	'jquery',
    'hpsum/view/node/jquery.hpsumInstallables',
    'hp/lib/jquery.hpCollapsible'],
function(presenter, router, urlFragment, notifications, localizer, session, rest) { "use strict";

    var DeployDomainView = (function() { 
    	
    	var DEPLOYBUTTON = '#integrityilo-deploy-domain-ok',
    		CLOSEBUTTON = '#integrityilo-deploy-domain-close',
    		DOWNGRADECHKBOXCOMP ='.downgradechkbox',
			REWRITECHKBOXCOMP ='.rewritechkbox',
			DOMAININFO_TABLE = '#hpsum-deploy-domain-table',
			DOMAIN_REBOOT_TABLE = '#hpsum-domain-reboot-table',
			NOTIFICATION = '#deploy-domain-notification',
			BASELINES = '#hpsum-deploy-domain-baselines',
			INSTALL_OPTIONS = '#hpsum-deploy-domain-installation-Options',
			REBOOT_OPTIONS = '#hpsum-deploy-domain-reboot-options',
			SPLASH_DIALOG = '#hpsum-deploy-domain-splash-dialog',
			SPLASH_SPINNER = '#hpsum-deploy-domain-splash-spinner'; 
			 

        /**
         * Constructor
         */
        function DeployDomainView() {
        	
        	var nodeItem = null;
        	
        	var  installationoptions = {
				force:false,
				downgrade:false,
				rewrite:false												
			};
        	
        	var optiondetails = { 
				hapi: {
					activate_sfw: false,
					installation_option:{
						downgrade: false,
						rewrite:false,
						force:false
					}
            	}
           	};
            
            var deploy_count = 0;
            var analyze_count = 0;
            var notification_msg = '';
            var failedDependencyCount = 0;
			var deploy_flag = false;
			var isSelectionChanged = false;
			var selectedComponentsCount = 0;
           
			function onItemChange(item) {
				nodeItem = item.hapi;
				
				if(nodeItem.domain_deploy_message) {
					notification_msg = nodeItem.domain_deploy_message;
				} else {
					notification_msg = '';
				}
				
				$(DEPLOYBUTTON).attr('disabled','disabled');
				
				populateDomainInfo(nodeItem);
				
				for(var i = 0; i < nodeItem.domain_partitions.length; i++) {
					var par = nodeItem.domain_partitions[i];
					
					if(par.node_id) {
						presenter.getNodeData(par, {
						success: onGetNodeDataSuccess,
						error: onGetNodeDataError
						});
					} else {
						notification_msg = notification_msg + '<p>' + 'Partition not ready to deploy: ' + par.monarchIP + '</p>';
					}					
				}
				
				if(!notification_msg) {
					$(NOTIFICATION).html(localizer.getString("hpsum.common.iloDomainNotifyMsg"));
					$(BASELINES).show();
					$(REBOOT_OPTIONS).show();
					//Install options not required to show (similar to common node deploy page)
					$(INSTALL_OPTIONS).hide();
					
					presenter.otheroption(nodeItem, {
						success: populateOtherOptions,	
						error: onPopulateError
						});
					
					var options = {
						command:'init',
						nodeItem:nodeItem,
						onSelectionChanged:onSelectionChanged,
						onPopulateInstallSet:onPopulateInstallSet
					};
					
					//Call plugin to show the component list ();
					$('#all-baselines').hpsumInstallables(options);
	                    
	               	$('.require-analysis').on('click', function(){
	               		$(DEPLOYBUTTON).attr('disabled','disabled');
	               	});	
	               	
	               	if($('.hp-selected').length > 0){
	               		$(DEPLOYBUTTON).removeAttr('disabled');
	               	}		
				} else {
					showDeployDomainError();
				}
			}
			
			function onGetNodeDataSuccess(item) {
				if(item.hapi.node_state != "UAN" && notification_msg.indexOf(item.hapi.ip) == -1) {
					notification_msg = notification_msg + '<p>' + 'Partition not ready to deploy: ' + item.hapi.ip + '</p>'; 
					showDeployDomainError();
				}
				
				$("input:checkbox.reboot-partition").each(function () {
					if($(this).val() == item.hapi.node_id) {
						if(item.hapi.activate_sfw) {
							$(this).attr('checked', 'checked');
						} else {
							$(this).removeAttr('checked');
						}
					}
				});
			}
			
			function onGetNodeDataError(data, item) {
				if(notification_msg.indexOf(item.monarchIP) == -1) {
					notification_msg = notification_msg + '<p>' + 'Partition not ready to deploy: ' + item.monarchIP + '</p>';
					showDeployDomainError();	
				}
			}
			
			function showDeployDomainError(){
				$(NOTIFICATION).html(notification_msg);
				$(DEPLOYBUTTON).attr('disabled','disabled');
				$(BASELINES).hide();
				$(INSTALL_OPTIONS).hide();
				$(REBOOT_OPTIONS).hide();				
			}
			
			function onPopulateError(errorMessage) {
                notifications.show(errorMessage, 'error');
				$(DEPLOYBUTTON).attr("disabled", 'disabled');
				$(CANCEL).trigger('click');
				
            }
            
            function populateDomainInfo(nodeItem) {
            	$(DOMAININFO_TABLE).html('');
            	$(DOMAIN_REBOOT_TABLE).html('');
            	
            	var reboot_count = 0;
            	for(var i = 0; i < nodeItem.domain_partitions.length; i++) {
            		var par = nodeItem.domain_partitions[i];
            		var domain_row = $('<tr></tr>').html('<td>' + par.monarchIP + '</td><td>' + par.number + '</td><td>'+ par.bays + '</td>');
            		
            		if(par.power_on && par.node_id) {
            			var reboot_row = $('<tr></tr>').html('<td><input class=\"reboot-partition require-analysis\" type=\"checkbox\" value=\"' + par.node_id +'\"></td><td>'+ par.monarchIP + '</td><td>' + par.number + '</td><td>'+ par.bays + '</td>');
            			$(DOMAIN_REBOOT_TABLE).append(reboot_row);
            			reboot_count++;	
            		} 		
            		$(DOMAININFO_TABLE).append(domain_row);
            	}
            	if(reboot_count == 0) {
            		$(DOMAIN_REBOOT_TABLE).html('<tr><td colspan=4><i>No partitions require reboot to activate</i></td></tr>');
            	}
            }
			
			function populateOtherOptions(data)	{
				if(data && data.hasOwnProperty("hapi")){
				
					if(data.hapi.hasOwnProperty("installation_option") && data.hapi.installation_option){
						installationoptions.downgrade = data.hapi.installation_option.downgrade;
						installationoptions.rewrite = data.hapi.installation_option.rewrite;
						installationoptions.force = data.hapi.installation_option.force;										
					}				
				}						
				
				$(DOWNGRADECHKBOXCOMP).attr('checked', installationoptions.downgrade);							
				$(REWRITECHKBOXCOMP).attr('checked', installationoptions.rewrite);					
			}
			
			function onDeploy() {
				deploy_count=0;
				deploy_flag = true;
				analysis();
			}
			
			function deployContinue() {
				for(var i = 0; i<nodeItem.domain_partitions.length; i++) {
					var par = nodeItem.domain_partitions[i];
					presenter.deploy(par, {
						success : onDeploySuccess,
                        error : onDeployError
                    });
				}
			}
			
			function onDeploySuccess(item) {
				deploy_count++;
				if(deploy_count == nodeItem.domain_partitions.length) {
					closeAnalysisSplash();
					deploy_flag = false;
					$(CLOSEBUTTON).trigger('click');
				}
            }


            function onDeployError(errorMessage) {
            	deploy_count++;
            	if(deploy_count == nodeItem.domain_partitions.length) {
            		closeAnalysisSplash();
            		deploy_flag = false;
	                notifications.show(errorMessage, 'error');                        				
					$(DEPLOYBUTTON).attr("disabled", 'disabled');				
					$(CLOSEBUTTON).trigger('click');
				}
            }
			
			function analysis() {
				
				analyze_count = 0;
				showAnalysisSplash();
				var inst = $('#all-baselines').data('plugin_hpsumInstallables');
				var componentsList = inst.getComponents();
				
				//call setattribute and analysis for each partition node				
				for(var i = 0; i<nodeItem.domain_partitions.length; i++) {
					var par = nodeItem.domain_partitions[i];
					setoptiondetails(par);
					presenter.setattribute(par, optiondetails, {
						partition : par,
                        success : function(data) {
								presenter.analysis(this.partition, componentsList, {
									node_id: this.partition.node_id,
									success : function(data) {
										analyzeSuccess(data, this.node_id);
										isSelectionChanged = false;
									},
									error : function(errorInfo) {
										analyzeError(errorInfo);
										isSelectionChanged = false;
									}
								});
							},
                        error : onSetAttributeError
                    });                     
                }				
			}
			
			function analyzeSuccess(item) {
				analyze_count++;
				if(analyze_count == nodeItem.domain_partitions.length) {
					getPartitionNodeStatus();	
				}
            }

            function analyzeError(errorMessage) {
            	analyze_count++;
            	if(analyze_count == nodeItem.domain_partitions.length) {
            		deploy_flag = false;
	                notifications.show(errorMessage, 'error');                        				
					$(DEPLOYBUTTON).attr("disabled", 'disabled');				
					$(CLOSEBUTTON).trigger('click');
				}
				$(SPLASH_SPINNER).hide();
				$(SPLASH_DIALOG).dialog('destroy');
            }
            
            function getPartitionNodeStatus()
			{
				//deep copy of partitions array
				var partitions = $.extend(true, [], nodeItem.domain_partitions);
				var progressTimer = setInterval(function () {
					for(var i = 0; i < partitions.length; i++) {
						var par = partitions[i];
						var node_uri = "/Session/" + session.getToken() + "/node/" + par.node_id;
						rest.getURI(node_uri + "/getstatus", {
							nodeid : par.node_id,
							success : function(data) {
								if(data.hapi.node_status.node_state === "ANALYSIS")
								{
								}
								else if(data.hapi.node_status.node_state === "UAN")
								{
									removePartition(partitions, this.nodeid);
								}
								else if(data.hapi.node_status.node_state === "ERROR")
								{
									removePartition(partitions, this.nodeid);
								}
							},
							error : function(errorInfo) {
								removePartition(partitions, this.nodeid);				
							}
						});
					}
					if(partitions.length <= 0) {
						clearInterval(progressTimer);
						deployContinue();
					}
		        }, 3000);
			}
			
			function removePartition(partitions, nodeid) {
				for (var n = 0 ; n < partitions.length ; n++) {
				    if (partitions[n].node_id == nodeid) {
				     	partitions.splice(n,1);
				      	break;
				    }
				}
			}
			
			function onSetAttributeSuccess(){
				//Update the node data
				//presenter.getNodeData(nodeItem, {success: onItemChange});			
			}
			
			function onSetAttributeError(){
				$(DEPLOYBUTTON).attr("disabled", 'disabled');	
			}
			
			function setoptiondetails(partition) {
				
				optiondetails.hapi.installation_option.downgrade =  $(DOWNGRADECHKBOXCOMP).is(':checked');	
				optiondetails.hapi.installation_option.rewrite = $(REWRITECHKBOXCOMP).is(':checked');
				if(optiondetails.hapi.installation_option.downgrade || optiondetails.hapi.installation_option.rewrite){
					optiondetails.hapi.installation_option.force = true;
				} else {
					optiondetails.hapi.installation_option.force = false;
				}
				
				$("input:checkbox.reboot-partition").each(function () {
						if($(this).val() == partition.node_id) {
							if($(this).is(':checked')) {
								optiondetails.hapi.activate_sfw = true;	
							} else {
								optiondetails.hapi.activate_sfw = false;
							}	
						}
				});
			}
			
			function onSelectionChanged(id, value, componentList){
				if(value == true){
					isSelectionChanged = true;
					$(DEPLOYBUTTON).attr("disabled", false);
				}
				selectedComponentsCount = componentList.component.length;
				if(componentList.component.length > 0 && componentList.failed_dependency == 0)
					$(DEPLOYBUTTON).attr("disabled", false);
				else
					$(DEPLOYBUTTON).attr("disabled", true);
									
                // Block deploy button if there is any unchecked ignore warnings checkbox
				// save disabled status to enable recovery it if ignore warnings changed
				$(DEPLOYBUTTON).attr("disabled_org", $(DEPLOYBUTTON)[0].disabled ? 1:0);
				if ($(".ignorewarnings")[0] && !$(".ignorewarnings").is(':checked')) {
					$(DEPLOYBUTTON).attr("disabled", true);
				}
			}
			
			function onPopulateInstallSet(node_id)
			{
				if(deploy_flag)
				{
					var install = $('#all-baselines').data('plugin_hpsumInstallables');

					failedDependencyCount = install.failedDependencyCount();
					if(failedDependencyCount <= 0 && selectedComponentsCount > 0)
					{
						$(DEPLOYBUTTON).attr("disabled", true);
						deployContinue();
					}
					deploy_flag = false;
				}
			}
			
			function showAnalysisSplash()
			{
				$(SPLASH_DIALOG).dialog({
			        modal : true,
			        position : "center",
			        draggable : false,
			        resizable : false,
			        show : 'fade',
					closeOnEscape: false,
			        dialogClass : 'hp-splash-dialog',
			        width : 400
			    });
				$('#hpsum-deploy-domain-splash-message').html(localizer.getString("hpsum.group.analysisProgressPW"));
				$(SPLASH_SPINNER).show();	
			}
			
			function closeAnalysisSplash(){
				$(SPLASH_SPINNER).hide();
				$(SPLASH_DIALOG).dialog('destroy');
			}
			
			this.resume = function () {
				presenter.on("itemChange", onItemChange);
				deploy_flag = false;
            };
            
            this.pause = function() {
            	presenter.off("itemChange", onItemChange);
            	$('.hpsumInstallables').hpsumInstallables('destroy');
            };
          
            /**
             * @public
             * Initialization funtion for the object
             * All the controls actions are initialized in this function.
             */
            this.init = function() {
            	
            	$(DEPLOYBUTTON).live('click', function(ev) {
                    onDeploy.call(this);
                    ev.preventDefault();
                });
                
                $(CLOSEBUTTON).click(function () {
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                });
                
            	$(".hp-collapsible").hpCollapsible();
            	this.resume();               					
            };
        }

        return DeployDomainView;
    }());
    
    return new DeployDomainView();
});