<?php

function fn_gettable_am($aql)
{
	global $installfolder;
	$data = $aql->Consume(2);
	
	$params = $data[0]->value;
	$assets = $data[1]->value;

	//print_r($data);	
			
	$table = "";
	$filters = FALSE;
	$datefrom = FALSE;
	$dateto = FALSE;
	
	if (isset($params['table']))
	{
		//Syntax <tablename>
		$table = $params['table'];
	}
	
	if (isset($params['from']))
	{
		//Syntax <tablename> <daterange>
		$datefrom = $params['from'];
		$dateto = $params['to'];
	}	
	
	require_once($installfolder.'/addons/table/api/tables.php');
	
	$tables = new TableSet();
	$tables->Load();

	$activetable = FALSE;

	foreach($tables->tables as $t)
	{
		//print_r($t);
		if (strtolower($t->name) == strtolower($table))
		{
			$activetable = $t;
			break;
		}
	}
	
	if ($activetable === FALSE)
	{
		$a = new AQLStackElement();
		$a->typename = "error";
		$a->islist = true;
		$a->value = "Can not find table '".$table."'";
		array_push($aql->stack,$a);
		return;
	}	

	$query = $activetable->GetQuery();
	
	if ($datefrom !== FALSE)
		$query->SetRange($datefrom,$dateto);
	
	if ($filters !== FALSE)
	{
		foreach($filters as $k => $v)
		{
			$query->AddFilter($k,$v);
		}
	}
	
	//echo "Assets: ";
	//print_r($assets);
	foreach($assets as $a)
	{
		$query->ForAsset($a);
	}
	
	$rows = $query->Get();
	
	$a = new AQLStackElement();
	$a->typename = "map";
	$a->islist = true;
	$a->value = $rows;
	array_push($aql->stack,$a);
	
	//print_r($rows);
	
	return;
}

function fn_gettable_m($aql)
{
	global $installfolder;
	$data = $aql->Consume(1);
	
	$params = $data[0]->value;	
			
	$table = "";
	$filters = FALSE;
	$datefrom = FALSE;
	$dateto = FALSE;
	
	if (isset($params['table']))
	{
		//Syntax <tablename>
		$table = $params['table'];
	}
	
	if (isset($params['from']))
	{
		//Syntax <tablename> <daterange>
		$datefrom = $params['from'];
		$dateto = $params['to'];
	}	
	
	require_once($installfolder.'/addons/table/api/tables.php');
	
	$tables = new TableSet();
	$tables->Load();

	$activetable = FALSE;

	foreach($tables->tables as $t)
	{
		//print_r($t);
		if (strtolower($t->name) == strtolower($table))
		{
			$activetable = $t;
			break;
		}
	}

	//print_r($params);
	
	if ($activetable === FALSE)
	{
		$a = new AQLStackElement();
		$a->typename = "error";
		$a->islist = true;
		$a->value = "Can not find table '".$table."'";
		array_push($aql->stack,$a);
		return;
	}

	$query = $activetable->GetQuery();
	
	if ($datefrom !== FALSE)
		$query->SetRange($datefrom,$dateto);
	
	if ($filters !== FALSE)
	{
		foreach($filters as $k => $v)
		{
			$query->AddFilter($k,$v);
		}
	}
	
	$rows = $query->Get();
	
	$a = new AQLStackElement();
	$a->typename = "map";
	$a->islist = true;
	$a->value = $rows;
	array_push($aql->stack,$a);
	
	//print_r($rows);
	
	return;
}
?>