<?php


//ob_start();



function findassetbyname($search)
{
	//$search = $s->asset;
	$foundid = -1;
	$mod = "";
	global $db;
	global $installfolder;	
	
	//Find the asset - this is probably based on name or ern...
	$identifiers = array();
	include_once($installfolder.'/model/property.php');
	$props = Properties::GetAllProperties();
	foreach($props as $px)
	{
		if ($px->type == "TAG")
		{
			$identifiers[] = $px->id;
		}
		if ($px->type == "ID")
		{
			$identifiers[] = $px->id;
		}
	}
	
	$perfectmatch = false;
	
	if (count($identifiers) > 0)
	{
	
		$qry = "SELECT id,name FROM assets JOIN assetvalues ON (assetvalues.assetid = assets.id) WHERE (assetvalues.value LIKE '%".$search."%')".$mod." AND (propertyid IN (".implode(',',$identifiers).")) ORDER BY name";		
		
		$query = $db->query($qry);
		
		$lastname = "";
		while($row = $query->fetch(PDO::FETCH_ASSOC)) 
		{
			if ($foundid == -1)			
				$foundid = $row['id'];
			
			if (strtolower($row['name']) == strtolower($qry))
			{
				$foundid = $row['id'];
				$perfectmatch = true;
				break;
			}
			//break;
		}
	};
	
	//echo $foundid;
	
	if ($perfectmatch == true)
		return $foundid;
	
	$qry = "SELECT id,name FROM assets WHERE (name = '".$search."')".$mod." ORDER BY name";
	//echo $qry;
	
	$query = $db->query($qry);
	
	$lastname = "";
	while($row = $query->fetch(PDO::FETCH_ASSOC)) 
	{
		if ($foundid == -1)
			$foundid = $row['id'];
		if ($row['name'] == $search)
		{
			$perfectmatch = true;
			$foundid = $row['id'];
			break;
		}
	}
	
	return $foundid;	
}


$entityBody = file_get_contents("php://input");
echo $entityBody;
$content = json_decode($entityBody);

print_r($content);
echo "\r\n";

$val = ob_get_clean();

file_put_contents($sitefolder."/grafana.log",$val);
header("Content-Type: application/json");

//echo $entityBody;
if (!property_exists($content,"type"))
{
	if (property_exists($content,"searchfor"))
	{
		$px = strpos($content->searchfor,"'");
		if ($px !== FALSE)
		{
			//This is AQL in the query!
			require_once($installfolder.'/addons/aql/api/aql.php');
			require_once($installfolder.'/model/property.php');
			
			$props = Properties::GetAllProperties();
			
			ob_start();
			$qry = new AQLQuery();
			$qry->Query($content->searchfor);
			ob_get_clean();
			
			echo '[';
			
			$counter = 0;
			foreach($qry->base->stack as $result)
			{
				if ($result->typename == "assetlist")
				{
					foreach($result->value as $id)
					{
						if ($counter > 0)
							echo ',';
						$ass = new Asset($id);
						echo '"'.$ass->name.'"';
						$counter++;
					}
				}
				if ($result->typename == "pointlist")
				{
				}
			}
			
			echo ']';
		}
		exit();
	}
}
else
{
	if ($content->type == 'property')
	{
		$query = $content->searchfor;
		
		//echo $query;
		
		require_once($installfolder.'/model/property.php');
		
		$lst = array();
		if ($query == "")
		{
			$props = Properties::GetAllProperties();
						
			foreach($props as $p)
			{
				switch($p->type)
				{
					case "MEASUREMENT":
					case "STATUS":
					case "ENUM":
					case "LOOKUP":
						$lst[] = $p->name;
						break;
				}
				
			}
					
		}
		else
		{
			$ast = findassetbyname($query);
			if ($ast > 0)
			{
				$ass = new Asset($ast);
				$props = $ass->GetProperties();
				foreach($props as $p)
				{
					switch($p->type)
					{
						case "MEASUREMENT":
						case "STATUS":
						case "ENUM":
						case "LOOKUP":
							$lst[] = $p->name;
							break;
					}
				}
				
				$alerts = $ass->GetAlerts();			
				foreach($alerts as $al)
				{
					if ($al['name'] != "")
						$lst[] = "ALERT: ".$al['name'];
				}				
			}
		}

		
		if (count($lst) > 0) sort($lst);
		
		echo '[ ';
		$indx = 0;
		foreach($lst as $l)
		{
			if ($indx != 0) echo ',';
			$indx++;
			echo '"'.$l.'"';
		}
		if (count($lst)> 0) echo ',';
		echo ' "All Analog", "All Discrete" ]';
		exit;
	}

	if ($content->type == 'relationship')
	{
		$query = $content->searchfor;
		
		require_once($installfolder.'/model/relationship.php');
		
		$props = Relationships::GetAllRelationships();
		
		if ($query == "")
		{
			$lst = array();
			foreach($props as $p)
			{		
				$lst[] = $p->name;
			}
		}
		else
		{
			$ast = findassetbyname($query);
			if ($ast > 0)
			{
				$ass = new Asset($ast);
				foreach($asset[$ast]['relationships'] as $k => $v)
				{
					foreach($props as $n)
					{
						if ($n->id == $k)
						{
							$lst[] = $n->name;
							break;
						}
					}
				}
			}
		}
		
		sort($lst);
		
		echo '[ "None", "Time"';
		$indx = 1;
		foreach($lst as $l)
		{
			if ($indx != 0) echo ',';
			$indx++;
			echo '"'.$l.'"';
		}
		echo ']';
		exit;
	}

	if ($content->type == 'context')
	{
		$query = $content->searchfor;
		
		//$lst[] = 'Actual';
		
		global $db;
		$query = $db->query('SELECT name,id,reqport FROM profiles');
		while($row = $query->fetch(PDO::FETCH_ASSOC)) 
		{
			$lst[] = $row['name'];
			//echo '    <profile name="'.$row['name'].'" id="'.$row['id'].'" port="'.$row['reqport'].'"/>';
		}
		
		//$lst[] = 'GTick';
		
		sort($lst);
		
		echo '[';
		$indx = 0;
		foreach($lst as $l)
		{
			if ($indx != 0) echo ',';
			$indx++;
			echo '"'.$l.'"';
		}
		echo ']';
		exit;
	}

	if ($content->type == 'asset')
	{
		$query = $content->searchfor;
		$_REQUEST['q'] = $query;
		
		if (strlen($query) > 1)
		{
			echo '[ ';
			$groups = array();
		
			$mod = "";
			$hits = array();
			
			$types = array();	
			
			if (!isset($_REQUEST['type'])) $_REQUEST['type'] = '0,3';
			if ($_REQUEST['type'] == -1)
			{
				unset($_REQUEST['type']);
			}
			if (isset($_REQUEST['type']))
			{
				$typ = $_REQUEST['type'];
				if($typ == "0")
				{
					$typ = "0,3";
				}
				if ($typ !== FALSE)
				{			
					$types = explode(',',$typ);
				}
			}
			
			$notunder = 0;
			if (isset($_REQUEST['notunder']))
			{		
				$notunder = $_REQUEST['notunder'];
			}
			
			$avoid = array();
			
			if ($notunder != 0)
			{
				//echo 'Not under!';
				$bits = explode('_',$notunder);
				$qry = "SELECT childasset FROM assetrelationships WHERE parentasset=".$bits[1].' AND relationship='.$bits[0];	
				$query = $db->query($qry);
				
				//echo $qry;
				
				while($row = $query->fetch(PDO::FETCH_ASSOC)) 
				{
					$avoid[] = $row['childasset'];
				}		
				
				$avoid[] = $bits[1];
			}
			
			$first = true;
			
			require_once($installfolder.'/model/asset.php');
			
			$identifiers = array();
			include_once($installfolder.'/model/property.php');
			$props = Properties::GetAllProperties();
			foreach($props as $px)
			{
				if ($px->type == "TAG")
				{
					$identifiers[] = $px->id;
				}
				if ($px->type == "ID")
				{
					$identifiers[] = $px->id;
				}
			}
			
			foreach($types as $t)
			{
				$mod = ' AND type = '.$t;
				if (count($identifiers) > 0)
				{
				
					$qry = "SELECT id FROM assets JOIN assetvalues ON (assetvalues.assetid = assets.id) WHERE (assetvalues.value LIKE '%".$_REQUEST['q']."%')".$mod." AND (propertyid IN (".implode(',',$identifiers).")) ORDER BY name";
					//echo $qry;
					
					$query = $db->query($qry);
					
					$lastname = "";
					while($row = $query->fetch(PDO::FETCH_ASSOC)) 
					{
						//if ($lastname == $row['name']) continue;		
						if (in_array($row['id'],$hits)) continue;
						if (in_array($row['id'],$avoid)) continue;
						$hits[] = $row['id'];
						
						$groups[] = array();
						$indx = count($groups)-1;
						$groups[$indx]['id'] = $row['id'];
						$thisasset = new Asset($row['id']);
						if ($first == true)
							$first = false;
						else
							echo ',';
						echo '"'.$thisasset->name.'"';
						if ($thisasset->ern != "")
					{
						echo ',"'.$thisasset->ern.'"';
					}
					}
				};
				
				
				$qry = "SELECT id FROM assets WHERE (name LIKE '%".$_REQUEST['q']."%')".$mod." ORDER BY name";
				//echo $qry;
				
				$query = $db->query($qry);
				
				$lastname = "";
				while($row = $query->fetch(PDO::FETCH_ASSOC)) 
				{
					//if ($lastname == $row['name']) continue;
					if (in_array($row['id'],$hits)) continue;
					if (in_array($row['id'],$avoid)) continue;
					$hits[] = $row['id'];
						
					$groups[] = array();
					$indx = count($groups)-1;
					$groups[$indx]['id'] = $row['id'];
					$thisasset = new Asset($row['id']);
					if ($first == true)
							$first = false;
						else
							echo ',';
						echo '"'.$thisasset->name.'"';
						if ($thisasset->ern != "")
					{
						echo ',"'.$thisasset->ern.'"';
					}
				}
				
				$qry = "SELECT id FROM assets JOIN assetvalues ON (assetvalues.assetid = assets.id) WHERE (assetvalues.value LIKE '%".$_REQUEST['q']."%')".$mod." ORDER BY name";
				
				$query = $db->query($qry);
				
				$lastname = "";
				while($row = $query->fetch(PDO::FETCH_ASSOC)) 
				{
					if (in_array($row['id'],$hits)) continue;
					if (in_array($row['id'],$avoid)) continue;
					$hits[] = $row['id'];
						
					$groups[] = array();
					$indx = count($groups)-1;
					$groups[$indx]['id'] = $row['id'];
					$thisasset = new Asset($row['id']);
					if ($first == true)
							$first = false;
						else
							echo ',';
						echo '"'.$thisasset->name.'"';
					if ($thisasset->ern != "")
					{
						echo ',"'.$thisasset->ern.'"';
					}
				}
			}


			echo ' ]';
			exit;
		}	
	}
}
?>[ ]