<?php

function fn_when_tf($aql)
{
	$data = $aql->Consume(2);
	$points = $data[1];
	$comparison = $data[0];
	
	if (!is_array($points->value))
		$pointset = array($points->value);
	else
		$pointset = $points->value;
	
	$timeseries = array();
	
	//echo "Point Set: ";
	//print_r($points);
	
	$indx = -1;
	foreach($pointset as $p)
	{
		$indx++;
		$timeseries[$indx] = array();		
		//echo 'Exploring Time Series For...';
		//print_r($p);
		$hist = $p->history;
		$p->history = FALSE;
		foreach($hist as $v)
		{
			$pass = false;
			$p->rawvalue = $v[1];
			$p->value = $v[1];
			$comparison->value->stack = [];
		
			$a = new AQLStackElement();
			$a->typename = "pointlist";
			$a->islist = true;
			$a->value = array($p);
			array_push($comparison->value->stack,$a);
				
			$comparison->value->memory['index'] = $a;
				
			$comparison->value->prnt = $aql;
			ob_start();
			$comparison->value->Execute(false);				
			ob_get_clean();
			
			if (count($comparison->value->stack) > 0)
			{
				if(count($comparison->value->stack[0]->value) > 0)
				{
					$pass = true;
				}
			}
			
			//echo $v[0].' - '.$pass.' - '.$v[1].'<br/>';
			$timeseries[$indx][$v[0]] = $pass;					
		}
	}
	
	//print_r($timeseries);
	
	$tlist = array();
	$fromtime = FALSE;
	$lasttime = FALSE;
	$currentvalue = FALSE;
	$anytime = FALSE;
	foreach($timeseries as $ts)
	{
		foreach($ts as $k => $v)
		{
			if ($fromtime === FALSE)
			{
				$lasttime = $k;
				$fromtime = $k;
				$currentvalue = $v;
				continue;
			}
			
			$anytime = $k;
			if ($currentvalue == $v) continue;
			
			if ($currentvalue == true)
			{
				$tl = array();
				$tl['from'] = $fromtime;
				$tl['to'] = $k;
				$tlist[] = $tl;		
				$fromtime = $k;
			}
			else
			{
				$fromtime = $k;
			}			
			$lasttime = $k;
			$currentvalue = $v;
		}
				
		if ($currentvalue == true)
		{			
			if ($fromtime != $anytime) 
			{				
				$tl = array();
				$tl['from'] = $fromtime;
				$tl['to'] = $anytime;
				$tlist[] = $tl;	
			}
		}
	}		
	
	
	
	$a = new AQLStackElement();
	$a->typename = "timelist";
	$a->islist = true;
	$a->value = $tlist;
	array_push($aql->stack,$a);
}
?>