// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {GroupShowOverviewView}
 * Provides functions to show overview/details pane for a group
 */

define(['hpsum/presenter/group/GroupPresenter',
	'hpsum/presenter/node/NodePresenter',
    'hp/core/UrlFragment',
    'hp/core/Router',
    'text!hpPages/core/no_details.html',
    'hp/core/Localizer',
    'hp/view/DialogView',
    'jquery',
    'hp/lib/jquery.hpGridPanels',
    'hp/lib/jquery.hpEllipsis',
    'lib/jquery.ThreeDots',
    'lib/jquery.columnizer',
    'lib/jquery.dateFormat',
    'hp/lib/date',
    'hp/lib/jquery.hpTooltip',
	'hpsum/common/utility',
    'hpsum/view/node/jquery.hpsumInstallSetComponents'],

function (groupPresenter, nodePresenter, urlFragment, router, noneHtml, localizer, DialogView) {
    "use strict";

	var GroupShowOverviewView = ( function() {

			//Consts can go here
			var ROOT = '#hpsum-group-show-overview',
			    SPINNER = '#hpsum-group-add-spinner',
			    NAME = '#hpsum-over-group-name',
			    DESCRIPTION = '#hpsum-over-group-description',
			    GROUP_HOTFIX = '#hpsum-over-group-hotfix',
			 	GROUP_BASELINE = '#hpsum-over-group-baseline',
			    NODES_TABLE = '#hpsum-group-nodes-table',
			    OK_NODES = '#hpsum-group-ok-nodes',
			    ERROR_NODES = '#hpsum-group-error-nodes',
			    WARNING_NODES = '#hpsum-group-warning-nodes',
			    INPROGRESS_NODES = '#hpsum-group-inprogress-nodes',
				SCHEDULED_NODES = '#hpsum-group-scheduled-nodes',
			   	UNKNOWN_NODES = '#hpsum-group-unknown-nodes',
				SCHEDULE_DATETIME = '#hpsum-over-group-scheduledatetime',
				TIMEZONE = '#hpsum-over-group-timezone',
				NODE_COMP = '#hpsum-node-components',
				NODE_DIALOG = '#hpsum-group-node-dialog';
			var NODE_INSTALLABLE_STATUS_NO_APP_COMP = 1,
				NODE_INSTALLABLE_STATUS_ATBASELINE = 2,
				NODE_INSTALLABLE_STATUS_UPDATE_REQ = 0;

			function GroupShowOverviewView() {

				var noItem,
				groupItem,
				updateTimer = null;
				var date_time_new = '',
					time_value = '',
					date_value = '',
					NodeDialogContents = null,
					NodeDialog = null,
					groupBaseline = '';
					
				var SUCCESS = 0;
				function onSelectionChange(selection) {
					$(NODES_TABLE).dataTable().fnClearTable();
					urlFragment.replaceHrefUris(ROOT, selection.uris);
				}

			function renderNodesDataTable(data){
				var	ok = 0,
					warning = 0,
					error = 0,
					inprogress = 0,
					scheduledNodes = 0,
					unknown = 0;
				if(data.hapi.hasOwnProperty('output_data')){
					//filling global ipsSortedAsc and ipsSortedAsc variables from utilty.js
					ipsSortedAsc = sortNodes(data.hapi.output_data.nodes.node,'asc','sortedIps');
					ipsSortedDesc = ipsSortedAsc.slice().reverse();
					var nodeDataTable = data.hapi.output_data.nodes.node;
							
					$(NODES_TABLE).dataTable().fnClearTable();
					var rowId =1 ;		
					for (var idx = 0; idx < nodeDataTable.length; idx++) {
						var	status = 'unknown',
							change = false,
							nodeStatus=nodeDataTable[idx].node_status,
							rebootRequired = "",
							nodeBaseline = localizer.getString('hpsum.group.noBaseline'),
							adtPackage = localizer.getString('hpsum.group.noAdtPackage'),
							removeNode = "",
							viewLog = "",
							uri = "",
							tableData = [],
							schedule_date_time = "Not Scheduled",
							nodeData=nodeDataTable[idx];
							
						 if (nodeData.node_state.match(/uan/i)) {
							if(nodeData.installable_state == NODE_INSTALLABLE_STATUS_UPDATE_REQ) {									
								status = 'warning';
								warning++;
							} else {
								status = 'ok';										
								ok++;
							}
						}
						else if(nodeData.node_state.match(/scheduled|REMOTE_STAGING_SCHEDULED/i) &&
							nodeData.node_phase.match(/scheduled|Inventory/i)) {
							status = 'scheduled';
							convertDateTime(nodeData.schedule_date_time);
							schedule_date_time = date_time_new;
							scheduledNodes++;
						}
						else if (nodeData.node_state.match(/inventory|analysis|install$|REMOTE_STAGING/i) ||
							nodeData.node_phase.match(/initialize/i)) {
							status = 'unknown';
							change = true;
							inprogress++;
						} else if (nodeData.node_state.match(/error/i) ||
							nodeData.node_phase.match(/initialize|InActive/i)) {
							status = 'error';
							error++;
						}  else if (nodeData.node_state.match(/installdone/i)) {
							if (nodeData.return_code < SUCCESS) {									
								status = 'error';
								nodeStatus = localizer.getString('hpsum.node.installDoneWithErrors');
								error++;
							} else {
								status = 'ok';
								ok++;
							}
							if (nodeData.return_code == 1) {
								rebootRequired = localizer.getString('hpsum.node.rebootRequired')
							}
						} else if (nodeData.node_state.match(/idle/i)) {
							if (nodeData.node_phase.match(/unknown|error/i)) {
								status = 'error';
								error++;
							} else {
								status = 'warning';
								warning++;
							}
						} else {
							unknown++;
						}

						if (nodeData.baselines) {
						    for (var i = 0; i < nodeData.baselines.length; i++) {
						        if (nodeData.baselines[i].match('/')) {
						            var baseline = groupPresenter.getBaselineDetailsforId(nodeData.baselines[i]);
						            if (baseline) {
						                if (baseline.name.match(/^Additional Package/i)) {
						                    adtPackage = '<a href="#/baseline/show/r' + baseline.uri + '/getBaselineData" class="company-a">' +
                                                         localizer.getString('hpsum.group.additionalPackage') + '</a>';
						                } else {
						                    nodeBaseline = '<a href="#/baseline/show/r' + baseline.uri + '/getBaselineData" class="company-a">' +
                                                         baseline.name + '</a>';
						                }
						            }
						        }
						        else {
						            nodeBaseline = '<a href="javascript:void(0);">' + nodeData.baselines[i] + '</a>';
						        }
							  }
						    }

					   
						//Removed the condition for checking for the default group(QXCR1001377000: HP SUM 7.2 Node Groups: Edit not proper for node group which is added first)
						removeNode = '<a id="hpsum-group-remove-node" data-custom-value="' + nodeData.node_id + '">' +
									 '<img src="/img/hp-piano/close.png" >' + '</a>';
														
						uri = nodeData.node_uri;
							
						if (nodeData.node_state.match(/INSTALLDONE/i)) {
							viewLog = '<a href="#/node/deploy-results/r' + uri + '/getdata">' + localizer.getString('hpsum.oneTouchUpdate.viewLog') + '</a>';
						}
						
						var name = 	'<a id="hpsum-group-node-' + rowId +'" class="company-a">'+nodeData.name+'</a>';
						$(NODES_TABLE).dataTable().fnAddData({
							status : status,
							change : change,
							uri : uri,
							node_id : nodeData.node_id,
							name: name,
							type : displayILO(nodeData.type),
							node_status : nodeStatus,
							state : nodeData.node_state,
							return_code : nodeData.return_code,
							reboot : rebootRequired,
							baseline : nodeBaseline,
							adtPackage: adtPackage,
							/* Hiding Feature Schedule
							schedule : schedule_date_time,
							*/
							view_log : viewLog,
							remove_node : removeNode
						});	
						
						var oTab = $(NODES_TABLE).dataTable();
						oTab.$('#hpsum-group-node-'+rowId).click(function(){
							var row=$(this).closest('tr');
							var data = oTab.fnGetData( row[0] );
							var uri=data.uri+'/getdata';
							nodePresenter.selectItem(uri);
							router.go('/node/show');
						
					});
						rowId++;
					}
				    //Click event for the Applicable components
					$(NODES_TABLE + " tbody tr").click(function (e) {
					    var srcElem;
					    var tableData = $(NODES_TABLE).dataTable().fnGetData(this);

					    if (tableData != null) {
					        //Check if firefox or (chrome and IE)
					        if (e.srcElement)
					            srcElem = e.srcElement;//Chrome and IE
					        else {
					            srcElem = e.target;//Firefox
					        }

					        if (srcElem.tagName == 'A' && (srcElem.href == "javascript:void(0);")) {
					            InitNodeDialog(data);
					            $(NODE_COMP).empty();

					            $(NODE_COMP).append("<div id='node-baseline' style='margin:10px;' ></div>");
					            var installSetName = srcElem.innerText,
                                    installSetId =  null;

					            nodePresenter.getNodeDataForGroup({
					                success: function (data) {
					                    if (data.hapi.output_data.hasOwnProperty('nodes')) {
					                        var nodes = data.hapi.output_data.nodes.node;
					                        for (var idx = 0; idx < nodes.length; ++idx) {
					                            var nodeData = nodes[idx];
					                            if (nodeData.node_id == tableData.node_id) {
					                                if ((nodeData.installsets.hasOwnProperty('installset') == true) && nodeData.installsets.installset.length > 0) {
					                                    var nodeInstallSet = nodeData.installsets.installset;
					                                    for (var count in nodeInstallSet) {
					                                        if ((nodeInstallSet[count].iloinstallset_name.match(installSetName))) {
					                                            installSetId = nodeInstallSet[count].iloinstallset_id;
					                                            
					                                                var item = {
					                                                    node_id: tableData.node_id,
					                                                    installset_id: installSetId
					                                                };

					                                                nodePresenter.getInstallSetDetails(item, {
					                                                    success: function (data) {
					                                                        // populate install set components table.
					                                                        var options = {
					                                                            command: 'init',
					                                                            data: data
					                                                        };

					                                                        $('#node-baseline').hpsumInstallSetComponents(options);
					                                                    }
					                                                });
					                                            
					                                            break;
					                                        }
					                                    }
					                                }
					                                break;
                                                  }
					                            }
					                    }

					                }
					            });
					          
					        }
					    }
					});

				}
				$(OK_NODES).text(ok);
				$(ERROR_NODES).text(error);
				$(WARNING_NODES).text(warning);
				$(INPROGRESS_NODES).text(inprogress);
				/* Hiding Feature Schedule
				$(SCHEDULED_NODES).text(scheduledNodes);
				*/
				$(UNKNOWN_NODES).text(unknown);
								
			}
			

				function populateNodesTable(groupNodes) {					
										
					groupPresenter.getNodesData(groupItem, {
							success : function(data) {	
									renderNodesDataTable(data);
							}
							,
							error : function(errorMsg) {
							}
					});						
					
					$(OK_NODES + '-img').attr('tooltip', localizer.getString('hpsum.group.okGroupNodes')).hpTooltip();
					$(ERROR_NODES + '-img').attr('tooltip', localizer.getString('hpsum.group.errorGroupNodes')).hpTooltip();
					$(WARNING_NODES + '-img').attr('tooltip', localizer.getString('hpsum.group.warningGroupNodes')).hpTooltip();
					$(INPROGRESS_NODES + '-img').attr('tooltip', localizer.getString('hpsum.group.inProgressGroupNodes')).hpTooltip();
					$(UNKNOWN_NODES + '-img').attr('tooltip', localizer.getString('hpsum.group.unKnownGroupNodes')).hpTooltip();
				}

				function onItemChange(item) {
					$(NODES_TABLE).dataTable().fnClearTable();
					$(GROUP_BASELINE).html(localizer.getString('hpsum.group.noBaseline'));
					$(GROUP_HOTFIX).html(localizer.getString('hpsum.group.noAdtPackage'));
					noItem.remove();
					groupItem = item.hapi;

					$(SPINNER).hide();
					$(NAME).text(groupItem.group_name);
					$(DESCRIPTION).text(groupItem.group_description);
					if(groupItem.group_schedule_date_time)
						convertDateTime(groupItem.group_schedule_date_time);
					if(date_time_new !== '')
						$(SCHEDULE_DATETIME).text(date_time_new);
					else
						$(SCHEDULE_DATETIME).text("Not Scheduled");
					$(TIMEZONE).text(groupItem.group_schedule_timezone);

					if (groupItem.group_baselines) {
					    for (var i = 0; i < groupItem.group_baselines.length; i++) {
				
					        if(groupItem.group_baselines[i].match('/'))
					        {
					            var baseline = groupPresenter.getBaselineDetailsforId(groupItem.group_baselines[i]);
					            if (baseline) {
					                   if (baseline.name.match(/^Additional Package/i)) {
					                        $(GROUP_HOTFIX).html('<a href="#/baseline/show/r' + baseline.uri
                                                                + '/getBaselineData" class="company-a">' + baseline.name + '</a>');
					                    } else {
					                        $(GROUP_BASELINE).html('<a href="#/baseline/show/r' + baseline.uri
                                                                + '/getBaselineData" class="company-a">' + baseline.name + '</a>');
					                    }
					                }
					        }
					        else{
					            $(GROUP_BASELINE).text(groupItem.group_baselines[i]);
					            groupBaseline = groupItem.group_baselines[i];
					          }
						}
					}

					$('#node-baseline').hpsumInstallSetComponents('destroy');
					populateNodesTable(groupItem.group_nodes.group_node);
					if (updateTimer) {
						clearInterval(updateTimer);
						updateTimer = null;
					}
					if (groupItem.group_state.match(/INVENTORY|SELFINVENTORY|ANALYSIS|INSTALL$|STAGE_ONLY$/i) ||
					   (groupItem.group_state.match(/IDLE/i) && item.group_phase.match(/Initialize/i))) {
						    updateTimer = setInterval(function() {
						    	var routerLocation = router.location();
						    	if (routerLocation.match(/group/i) &&
						    		routerLocation.match(/show/i) &&
						    		routerLocation.match(/overview/i)) {
						    		populateNodesTable(groupItem.group_nodes.group_node);
						    	}
						    	else {
						    		if (updateTimer) {
						    		clearInterval(updateTimer);
						    		updateTimer = null;
						    		}
						    	}
						    }, 15000);
					} else if (!groupItem.group_state.match(/INVENTORY|SELFINVENTORY|ANALYSIS|INSTALL$|STAGE_ONLY$/) &&
							   !(groupItem.group_state.match(/IDLE/i) && groupItem.group_phase.match(/Initialize/i))) {
							   	if (updateTimer) {
						    		clearInterval(updateTimer);
						    		updateTimer = null;
						    	}
					}

					router.go((urlFragment.replaceView(router.location(), 'show/overview')));
				}

				function onItemError(error) {
					$(ROOT).append(noItem);
				}

				function getItemUrl(oObj) {
					return '<a href="#/node' + '/show/r' + oObj.aData.uri + '/getdata">' + oObj.aData.name + '</a>';
				}
				
				function convertDateTime(date_time)
				{
					date_value = '';
					time_value = '';
					date_time_new = '';
					if(date_time !== "")
					{
						var date_time_split = date_time.split(' ');
						var time_hrs_mins = date_time_split[1].split(':');
						var time_hrs = time_hrs_mins[0];
						date_value = date_time_split[0];
						time_value = '';
						date_time_new = '';
						if((date_time_split[2] == 'PM') && (parseInt(time_hrs) < 12))
						{
							time_hrs = parseInt(time_hrs) + 12;
						}
						else if(date_time_split[2] == 'AM')
						{
							if (parseInt(time_hrs) < 10 && parseInt(time_hrs) < 12)
							{
								time_hrs = '0' + parseInt(time_hrs);
							}
							else if (parseInt(time_hrs) == 12)
							{
								time_hrs = parseInt(time_hrs) - 12;
								time_hrs = '0' + parseInt(time_hrs);
							}
						}
						time_value = time_hrs + ':' + time_hrs_mins[1];
						date_time_new = date_value + ' ' + time_value;
					}
				}


				function InitNodeDialog() {
				    if (!NodeDialog) {
				        var closefunc = function (elem) {
				            $('#node-baseline').hpsumInstallSetComponents('destroy');
				            NodeDialog = null;
				        };
				        NodeDialog = new DialogView();
				      
				            NodeDialog.init({
				                contents: NodeDialogContents,
				                position: "center",
				                ok: function () { closefunc() },
				                cancel: function () { closefunc() }
				            });

				            
				    }
				}

				/*
				 *  Public Functions
				 */

				this.init = function() {
					noItem = $(noneHtml);
					$(DESCRIPTION).ThreeDots({
						max_rows : 3,
						alt_text_t : true
					});
					$('#hpsum-over-group-baselinelabel').attr('tooltip', localizer.getString('hpsum.group.groupBaselinehelp')).hpTooltip();
					$('#hpsum-over-group-hotfixlabel').attr('tooltip', localizer.getString('hpsum.group.groupHotfixhelp')).hpTooltip();
					var dummyNodeData = [];
					$(NODES_TABLE).dataTable({
						oLanguage : {
						    sEmptyTable: localizer.getString("hpsum.group.noNodesInGroup"),
						    sSearch: localizer.getString('hpsum.common.search')
						},
						bPaginate : false,						
						bFilter : true,
						bInfo : false,
						bAutoWidth : false,
						bRetrieve : true,
						aaData : dummyNodeData,
						aoColumns : [
						{mDataProp: 'status',
							fnRender: function (oObj) {
							    var statusCode;
								if (oObj.aData.change == true )
								{
									statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-changing"></div></div>';
								}
								else if(oObj.aData.status == "ok")
								{
                                    statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-ok"><span class="hp-value">ok</span></div></div>';
								}
                                else if(oObj.aData.status == "error")
                                {
									statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-error"><span class="hp-value">error</span></div></div>';
								}
                                else if(oObj.aData.status == "warning")
								{
                                	statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-warning"><span class="hp-value">warning</span></div></div>';
                                }
								else if(oObj.aData.status == "unknown")
                                {
									statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-unknown"><span class="hp-value">unknown</span></div></div>';
								}
								else if(oObj.aData.status == "scheduled")
								{
                                	statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-scheduled"><span class="hp-value">scheduled</span></div></div>';
								}
                           		return statusCode;
                           		
								/* Disable for now
								 * 
								 return '<div class="hp-switch"> <ol class="hp-up-ports">' +
								'<li class="hp-up-port">' + ' <div class="hp-condensed">' + statusCode +
								' </div>' + 
								'<div class="hp-full">' +
								statusCode + 
								'<div class="hp-form-contents"> ' +
								'<fieldset>' + '<ol> ' + ' <li> ' +
								'<div><a href="#/node' + '/show/r' + oObj.aData.uri + '/getData">' + oObj.aData.name + '</a><div></li>' +
								' <li> ' + '<div>' + oObj.aData.type + '</div>' + ' </li> ' +
								' <li> ' + '<div>' + oObj.aData.state + '</div>' + ' </li> ' +
								' <li> ' + '<div>' + oObj.aData.node_status + '</div>' + ' </li> ' +
								' <li> ' + '<div>' + oObj.aData.reboot + '</div>' + ' </li> ' +
								'</ol></fieldset></div></li></ol></div>';
								*/
							},
							sWidth: '10px', sClass: "hp-icon"
						},
						{
						mDataProp : 'name',
						"sType": "ip-sorting"
						}, {
						mDataProp : 'type'
						}, {
						mDataProp : 'node_status'
						}, {
							mDataProp : 'baseline'
							//sWidth: '70px'
						}, {
							mDataProp : 'adtPackage'
						},
                        /* Hiding Feature Schedule
                        {
						    mDataProp: 'schedule'
		                    }, */
                        {
							mDataProp : 'view_log'
						}, {
							mDataProp : 'remove_node'
						}],
						aaSorting : [[1, "asc"]],
						bScrollCollapse : true

					});
					
					//subsribe to 'ip-sorting' custom sorting function from utility.js file
					extendSorting();
					
					$('#hpsum-group-remove-node').live('click', function(ev) {
						groupPresenter.removeNodes(groupItem, {
							nodes : $(this).data("custom-value")
						}, {
							success : function(data) {
								groupPresenter.fireItemChange();
							},
							error : function(errorMessage) {
							}
						});
						ev.preventDefault();
					}); 
           			
					this.resume();
				};

				this.resume = function() {
					$(NODES_TABLE).dataTable().fnClearTable();
					$(GROUP_BASELINE).html(localizer.getString('hpsum.group.noBaseline'));
					$(GROUP_HOTFIX).html(localizer.getString('hpsum.group.noAdtPackage'));
					groupPresenter.refreshAllBaselines();
					groupPresenter.on("selectionChange", onSelectionChange);
					groupPresenter.on("itemError", onItemError);
					groupPresenter.on("itemChange", onItemChange);
					$('#node-baseline').hpsumInstallSetComponents('destroy');
					NodeDialogContents = $(NODE_DIALOG).detach().show();
				};

				this.pause = function() {
					groupPresenter.off("selectionChange", onSelectionChange);
					groupPresenter.off("itemChange", onItemChange);
					groupPresenter.off("itemError", onItemError);
				};

			}

			return new GroupShowOverviewView();
		}());

	return GroupShowOverviewView;
});
