<?php
header('Access-Control-Allow-Origin','*');
session_write_close();
include("aql.php");

$query = $_REQUEST['query'];

ob_start();
$qry = new AQLQuery();
$qry->Query($query);
$diagnostics = ob_get_clean();

$allprops = Properties::GetAllProperties();

$points = array();

$first = true;
$indx = 0;

header("Content-Type: text/json");
header('Access-Control-Allow-Origin: *');

require_once($installfolder.'/model/property.php');
$allprops = Properties::GetAllProperties();

$simple = false;
if (isset($_REQUEST['simple']))
	$simple = true;

if (!$simple)
{
	echo '{  "query": "'.str_replace('"','\\"',$query)."\",\r\n";
	//echo '  "diag": "'.str_replace('"','\\"',trim($diagnostics))."\",\r\n";
	echo '  "results": [ ';
}
foreach($qry->base->stack as $result)
{
	if (!$simple)
	{
		if ($first == true)
			$first = false;
		else
			echo ',';

		echo '{ "type": "'.$result->typename.'",';
		if ($result->name != "")
		{
			echo '"name": "'.$result->name.'",';
		}
		echo '"value": ';
	}
	$indx++;
	if ($result->typename == "assetlist")
	{		
		$arr = array();
		foreach($result->value as $r)
		{
			$ele = array();
			$ele['id'] = $r;
			$ass =  new Asset($r);
			$ele['name'] = $ass->name;
			$ele['ern'] = $ass->ern;
			$arr[] = $ele;
		}
		
		print(json_encode($arr));
		unset($arr);
		if (!$simple) echo ' }';
		continue;
	}
	
	if ($result->typename == "proplist")
	{		
		
		$arr = array();
		foreach($result->value as $r)
		{
			$ele = array();
			$ele['id'] = $r;
			foreach($allprops as $prop)
			{
				if ($prop->id == $r)
				{
					$ele['name'] = $prop->name;
					$ele['type'] = $prop->type;
					if (($prop->type == "STATUS") || ($prop->type == "ENUM") || ($prop->type == "LOOKUP"))
					{
						$mp = $prop->GetValueMap();
						$ele['map'] = $mp;
					}					
					$arr[] = $ele;
					break;
				}
			}			
		}
		
		print(json_encode($arr));
		unset($arr);
		if (!$simple) echo ' }';
		continue;
	}
	
	if ($result->typename == "rellist")
	{		
		require_once($installfolder.'/model/relationship.php');
		$allrels = Relationships::GetAllRelationships();

		$arr = array();
		foreach($result->value as $r)
		{
			$ele = array();
			$ele['id'] = $r;
			foreach($allrels as $rel)
			{
				if ($rel->id == $r)
				{
					$ele['name'] = $rel->name;
					$ele['type'] = $rel->type;							
					$arr[] = $ele;
					break;
				}
			}			
		}
		
		print(json_encode($arr));
		unset($arr);
		if (!$simple) echo ' }';
		continue;
	}
	
	if ($result->typename == "timelist")
	{				
		foreach($result->value as $r)
		{			
			$arr[] = $r;			
		}
		
		print(json_encode($arr));
		unset($arr);
		if (!$simple) echo ' }';
		continue;
	}
	
	if ($result->typename == "pointlist")
	{
		$points = array();
		foreach($result->value as $v)
		{
			$points[] = $v;
		}
	
		LiveValuesForPoints($points);

		$arr = array();
		foreach($points as $p)
		{
			$ele = array();
			$ele['assetid'] = $p->assetid;
			$ele['sourceid'] = $p->sourceid;
			if (is_array($p->value))
			{
				$ele['value'] = $p->value[0];
				$ele['rawvalue'] = $p->value[0];
			}
			else
			{
				$ele['value'] = $p->value;
				$ele['rawvalue'] = $p->rawvalue;
			}
			$ele['propid'] = $p->propertyid;
			$ele['fullvalue'] = $p->fullvalue;
			$ele['type'] = $p->type;
			$ele['name'] = $p->name;
			if (($p->dynamic !== FALSE) && ($p->dynamic !== ""))
				$ele['code'] = $p->dynamic;
			
			foreach($allprops as $prop)
			{
				if ($prop->id == $p->propertyid)
				{					
					if (($prop->type == "STATUS") || ($prop->type == "ENUM") || ($prop->type == "LOOKUP"))
					{
						$mp = $prop->GetValueMap();
						$ele['map'] = $mp;
						if (isset($mp[$ele['rawvalue']]))
						{
							$ele['value'] = $mp[$p->rawvalue];
						}
					}
					
					if ($prop->type == "MEASUREMENT")
					{
						$def = $prop->GetDefault();
						$ele['units'] = $def[1];
						$ele['min'] = $def[2];
						$ele['max'] = $def[3];
						$ele['places'] = $def[4];
					}
					
					$ele['propname'] = $prop->name;
					
					//echo $sitefolder.'/cache/display/'.$p->propertyid.'.xml';
					if (file_exists($sitefolder.'/cache/display/properties/'.$p->propertyid.'.xml'))
					{						
						//Include colour mapping information
						$xml=simplexml_load_file($sitefolder.'/cache/display/properties/'.$p->propertyid.'.xml');
				
						$cmap = array();
						
						if (property_exists($xml,'colours'))
						{							
							//echo 'Colours Found!';
							$attrs = $xml->colours->attributes();
							$z = "".$attrs['zero'];
							$o = "".$attrs['one'];
							if (($z == "")) $z = 'blue';
							if (($o == "")) $o = 'cyan';							
							$cmap[0] = trim($z);
							$cmap[1] = trim($o);							
						}	
					
						if (property_exists($xml,'value'))
						{														
							foreach($xml->value as $vl)
							{
								$attrs = $vl->attributes();
								$pieces = explode('-',$attrs['value']);
								if ($pieces[0] == "")
								{
									unset($pieces[0]);
									$pieces = array_values($pieces);
									$pieces[0] = '-'.$pieces[0];
								}								
								if (count($pieces) > 1)
								{
									for($x=0;$x<count($pieces);$x++)
									{
										$cmap[$pieces[$x]] = "".$attrs['colour'];
									}
								}
								else
								{
									$cmap["".$attrs['value']] = "".$attrs['colour'];
								}
							}	
						}
						
						if (property_exists($xml,'gradient'))
						{							
							//echo 'Colours Found!';
							$stops = $xml->gradient->attributes()['stops'];			
							
							$range = $ele['max'] - $ele['min'];
							
							$bits = explode('%25',$stops);							
							foreach($bits as $bt)
							{
								$pieces = explode('_',$bt);
								while((count($pieces) > 0) && ($pieces[0] == ""))
								{
									unset($pieces[0]);
									$pieces = array_values($pieces);
								}
								
								if (count($pieces) < 2) continue;
								
								$cmap[floor((($pieces[1]/100) * $range) + $ele['min'])] = $pieces[0];								
							}							
						}	
						
						if (count($cmap) > 0)
						{
							$ele['colours'] = $cmap;
						}
					}
					
					break;
				}
			}
			
			$ass =  new Asset($p->assetid);
			$ele['name'] = $ass->name;
			$ele['ern'] = $ass->ern;
			if ($p->history !== FALSE)
				$ele['history'] = $p->history;
			
			$arr[] = $ele;
		}
		echo json_encode($arr);
		unset($arr);
		if (!$simple) echo ' }';
		continue;
	}
	
	if ($simple)
		break;
	
	echo json_encode($result->value);
	echo ' }';
}

if (!$simple)
	echo ' ]}';



?>