// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * utility.js file created for adding utility functions to be accessed across multiple files.
 * This file can be added as ''hpsum/view/common/utility' in the define([]) section of parent file which want to use any   
 * common function from this file.
 */

	var ipsSortedAsc = [];
	var ipsSortedDesc = [];
 
	//function to convert ipv4/ipv6 address into decimal number for comparison/sorting
	function convertIPToDecimal(ipAddress, type){
		var newIp = '';
		var splitIp = [];
		if(type == 'ipv4')
		{
			splitIp = ipAddress.split('.');
			for(var index = 0; index < splitIp.length; index++)
			{
				if(splitIp[index].length==3)
				{
					newIp = newIp + splitIp[index];
				}
				else if(splitIp[index].length==2)
				{
					newIp = newIp +'0'+ splitIp[index];
				}
				else if(splitIp[index].length==1)
				{
					newIp = newIp +'00'+ splitIp[index];
				}
				
			}
		}
		else if(type == 'ipv6')
		{
			splitIp = ipAddress.split(':');
			var noOfAllZeroActaves = 0;
			var zeroOctetPosition = splitIp.indexOf('');
			var zeroOctet = '';
			//we found empty string in array means we had originally :: in IP address
			if(zeroOctetPosition != -1)
			{
				var octetCount = splitIp.length - 1;
				var noOfAllZeroActaves = 8 - octetCount;
			}
			
			for(index = 0; index < noOfAllZeroActaves; index ++)
			{
				zeroOctet = zeroOctet + '00000';
			}
			
			for(index = 0; index < splitIp.length; index++)
			{
				if(index == zeroOctetPosition)
				{
					newIp = newIp + zeroOctet;
					continue;
				}
				else
				{
					//convert hex to dec for comparison
					var decIpv6 = parseInt(splitIp[index], 16).toString();
					var prependZeros = '';
					for(var count = 0; count < 5 - decIpv6.length;count ++)
					{
						prependZeros = '0' + prependZeros;
					}
					
					newIp = newIp + prependZeros + decIpv6;
				}
			}
		}
		return newIp;
	}
	
	//function to swap two items from array given index to swap
	function swapItems(itemList,firstIndex,secondIndex)
	{
		var swapping = itemList[firstIndex];				   
		itemList[firstIndex] = itemList[secondIndex];
		itemList[secondIndex] = swapping;	
	}
	
	//function to custom sort ip addresses
	function sortNodes(dataForSorting, sortType,returnType)
	{
	var domainNameNodes = [];
	var ipv4Mapping = {};
	var ipv6Mapping = {};
	var ipv4Nodes = [];
	var ipv6Nodes = [];
	var allNodes = [];
	var sortedIPs = [];
	var data = dataForSorting;
	//for loop to add ipv4/ipv6/domain name type to respective arrays
	for(var index_outer = 0; index_outer < data.length; index_outer += 1)
			 {
				 var ipAddressFieldName = '';
				 if(data[index_outer].hasOwnProperty('name'))
				 {
					 ipAddressFieldName = 'name';
				 }
				else if(data[index_outer].hasOwnProperty('node_name'))
				 {
					 ipAddressFieldName = 'node_name';
				 }
				 if(data[index_outer][ipAddressFieldName].indexOf('.') != -1)
					  {
						  //reg ex for number format e.g 00.000.000.000
						  if(/^[0-9.]+$/.test(data[index_outer][ipAddressFieldName]))
						  {
						  ipv4Mapping[data[index_outer][ipAddressFieldName]] = convertIPToDecimal(data[index_outer][ipAddressFieldName],'ipv4');
						 ipv4Nodes.push(data[index_outer]);
						  }
						  //reg ex for dns format e.g matrix.cce.hp.com OR matrix123.cce.hp.com
						  else if(isDNSName(data[index_outer][ipAddressFieldName]))
						  {
							 //e.g mohali.indi.hp.com
							domainNameNodes.push(data[index_outer]);  
						  }
					  }
					  else if(data[index_outer][ipAddressFieldName].indexOf(':') != -1)
					  {
						 ipv6Mapping[data[index_outer][ipAddressFieldName]] = convertIPToDecimal(data[index_outer][ipAddressFieldName],'ipv6'); 
						 ipv6Nodes.push(data[index_outer]);
					  }
					  else
					  {
						  //e.g localhost
						  domainNameNodes.push(data[index_outer]);
					  }
			 }
			 //sort ipv4 addresses
			 for(var index_outer = 0; index_outer < ipv4Nodes.length; index_outer += 1){
			  for(var index_inner = index_outer+1; index_inner < ipv4Nodes.length; index_inner += 1)
				{
					if((sortType == 'desc' && (ipv4Mapping[ipv4Nodes[index_outer][ipAddressFieldName]] < ipv4Mapping[ipv4Nodes[index_inner][ipAddressFieldName]])) || 
					(sortType == 'asc' && (ipv4Mapping[ipv4Nodes[index_outer][ipAddressFieldName]] > ipv4Mapping[ipv4Nodes[index_inner][ipAddressFieldName]])))
					{
						swapItems(ipv4Nodes,index_inner,index_outer);
					}
				}
			 }
			 //sort ipv6 addresses
			 for(var index_outer = 0; index_outer < ipv6Nodes.length; index_outer += 1){
			  for(var index_inner = index_outer+1; index_inner < ipv6Nodes.length; index_inner += 1)
				{
					 if ((ipv6Mapping[ipv6Nodes[index_outer][ipAddressFieldName]] < ipv6Mapping[ipv6Nodes[index_inner][ipAddressFieldName]]) && sortType == 'desc' ||
					 ((ipv6Mapping[ipv6Nodes[index_outer][ipAddressFieldName]] > ipv6Mapping[ipv6Nodes[index_inner][ipAddressFieldName]]) && sortType == 'asc'))
					 {				              
						swapItems(ipv6Nodes,index_inner,index_outer);
					 }
				}
			 }
			 //sort domain names
			 for(var index_outer = 0; index_outer < domainNameNodes.length; index_outer += 1){
			  for(var index_inner = index_outer+1; index_inner < domainNameNodes.length; index_inner += 1)
				{
					if (sortType == 'desc' && (domainNameNodes[index_outer][ipAddressFieldName] < domainNameNodes[index_inner][ipAddressFieldName]) || 
					(sortType == 'asc' && (domainNameNodes[index_outer][ipAddressFieldName] > domainNameNodes[index_inner][ipAddressFieldName])))
					{				              
						swapItems(domainNameNodes,index_inner,index_outer);	
					}
				}
			 }
			 if(sortType == 'desc')
			 {
				allNodes.push.apply(allNodes, domainNameNodes.concat(ipv6Nodes).concat(ipv4Nodes));
			 }
			 else
			 {
				 allNodes.push.apply(allNodes, ipv4Nodes.concat(ipv6Nodes).concat(domainNameNodes));
			 }
			 data = allNodes;
			 for(var nodes=0;nodes<allNodes.length;nodes++)
			 {
				 sortedIPs.push(allNodes[nodes][ipAddressFieldName]);
			 }
			 if(returnType == 'sortedIps')
			 {
				return sortedIPs;
			 }
			 else
			 {
				 return data;
			 }
}

/* For this function to work, we need to have sorted ipsSortedAsc, ipsSortedDesc arrays available. 
*  We create them in SortNodes() function above. So in the parent page where we are adding custom sorting function 
* 'ip-sorting-asc' to dataTable, SortNodes() needs to be called before filtering happens.
*/
function extendSorting()
{
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"ip-sorting-asc": function (ip1,ip2) {
	return shouldSwapIps(ip1,ip2,ipsSortedAsc);
},

"ip-sorting-desc": function (ip1,ip2) {
	return shouldSwapIps(ip1,ip2,ipsSortedDesc);
	}
});
}

function shouldSwapIps(ip1,ip2,sortedIps)
{
	var firstNodeName = ip1;
	var secondNodeName = ip2;
if(ip1.indexOf('<a href') != -1 && ip2.indexOf('<a href') != -1)
{	
	firstNodeName = ip1.split('>')[1].split('<')[0];
	secondNodeName = ip2.split('>')[1].split('<')[0];
}
    return ((sortedIps.indexOf(firstNodeName) > sortedIps.indexOf(secondNodeName)) ? 1 : ((sortedIps.indexOf(firstNodeName) < sortedIps.indexOf(secondNodeName)) ? -1 : 0));
}

function isDNSName(ip) 
{
    var returnVal= false;       	
	var patt = /^[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)*\.([a-zA-Z]{2,})$/;
	//FQDN match
	if(ip.match(patt)){
		returnVal = true;     
	}		
	else {
		//check for unqualified domain name or netbios hostname
		var hostnamepatt = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";
		if(ip.match(hostnamepatt)){
			returnVal = true;
		}
   }

	return returnVal;
}

function displayILO(name){
	
	if(name.match(/ilo|ilo2|ilo3|ilo4|ilo5/i)){
		name = name.trim();
		var nameLength = name.length;
		var iloIndex = name.toUpperCase().indexOf("ILO");
		
		if(nameLength > (iloIndex + 3))
		{
			var iloVersion = name.charAt(iloIndex + 3);
			name = "iLO " + iloVersion;
		}
		else{
			name = "iLO";
		}
	}
	return name;
}
