<?php

function fn_addresses_t($aql)
{
	global $installfolder;
	$data = $aql->Consume(1);
	
	$points = $data[0]->value;
	
	global $db;
	$rows = array();
	
	$plist = array();
	$alist = array();
	
	foreach($points as $p)
	{				
		
		if (!in_array($p->propertyid,$plist))
		{
			$plist[] = $p->propertyid;
		}
		
		if (!in_array($p->assetid,$alist))
		{
			$alist[] = $p->assetid;
		}
	}
	
	if (count($plist) == 0)
	{
		$a = new AQLStackElement();
		$a->typename = "map";
		$a->islist = true;
		$a->value = array();
		array_push($aql->stack,$a);
	}
	
	if (count($alist) == 0)
	{
		$a = new AQLStackElement();
		$a->typename = "map";
		$a->islist = true;
		$a->value = array();
		array_push($aql->stack,$a);
	}
	
	$query = $db->query("SELECT address,sourceid,profile,propertyid, assetid, name,mode FROM datalinks JOIN assets ON (assets.id = sourceid) WHERE assetid IN (".implode(',',$alist).") AND propertyid IN (".implode(',',$plist).") ORDER BY assetid, propertyid");		
	
	while($row = $query->fetch(PDO::FETCH_ASSOC)) 
	{
		foreach($points as $p)
		{
			if ($p->propertyid == $row['propertyid'])
			{
				if ($p->assetid == $row['assetid'])
				{
					$rw = array();					
					$rw['asset'] = $p->assetid;
					$rw['property'] = $p->propertyid;
					$rw['profile'] = $row['profile'];					
					$rw['mode'] = $row['mode'];
					if ($rw['mode'] == 0) $rw['mode'] = 'live';
					if ($rw['mode'] == 1) $rw['mode'] = 'hist';
					$rw['source'] = $row['name'];
					$rw['address'] = $row['address'];
					$rows[] = $rw;
				}
			}
		}
		//$results[] = $row;
	}
				
	$a = new AQLStackElement();
	$a->typename = "map";
	$a->islist = true;
	$a->value = $rows;
	array_push($aql->stack,$a);
	
	//print_r($rows);
	
	return;
}
?>