<?php

class iriSonyengineEventListener
{
	static function listenToFind(sfEvent $event) {
		
		$segment = $event["segment"];
		$tag = $event["tag"];
		if(isset($event["distantce"])) {
			$distance = $event["distance"];
		}
		else {
			$distance = "0.05";
		}
		if(!isset($event["more"]))
		    $more = "false";
		else
			$more = $event["more"]?"true":"false";
		
		$client = SonyengineClient::getInstance();
		$result = $client->engineFind($segment,$tag,$distance,$more);
		
		$event->setReturnValue($result);
	}
	
	static function listenToEngineTrain(sfEvent $event) {
		$client = SonyengineClient::getInstance();
		$client->engineTrain();
	}
	
	static function listenToEngineReset(sfEvent $event) {
		$client = SonyengineClient::getInstance();
		$client->engineReset();
	}
	
	static function listenToSegmentCreate(sfEvent $event) {
		
		$client = SonyengineClient::getInstance();
		$obj = $event['object'];
		
		$retrain = isset($event['retrain'])?$event['retrain']:true;

		$objs = null;
		
		if(is_array($obj)) {
			$objs = $obj;
		}
		else {
			$objs = array();
			$objs[] = $obj;
		}
		
		$array = array();
		foreach($obj as $obj_instance) {

			if(is_array($obj_instance)) {
                $fields = $obj_instance;
            }
            elseif(method_exists($obj_instance,'getSonyengineFields')) {
			    $fields = $obj_instance->getSonyengineFields();
            }
            
            if(isset($fields) && isset($fields['id'])) {
			    $array[] = $fields["id"];
            }
		}
		
		if(count($array) > 0) {
		    $client->segmentCreate($array, $retrain);
		}
	}
	
	static function listenToTagAdd(sfEvent $event) {
		
		$client = SonyengineClient::getInstance();
		$obj = $event['object'];

        $retrain = isset($event['retrain'])?$event['retrain']:true;
				
		$objs = null;
		
		if(is_array($obj)) {
			$objs = $obj;
		}
		else {
			$objs = array();
			$objs[] = $obj;
		}
		
		$array = array();
		foreach($obj as $obj_instance) {
			
			if(is_array($obj_instance)) {
			    $fields = $obj_instance;
			}
			elseif(method_exists($obj_instance,'getSonyengineFields')) {
				$fields = $obj_instance->getSonyengineFields();
			}
			
			if(count($fields)>0) {
				$array[] = array("segment"=>$fields["segment_id"],"name"=>$fields["name"]);
			}
		}
		
		if(count($array) > 0) {
		  $client->tagAdd($array, $retrain);
		}
	}
}