<?php
class WebImageAccessController extends Controller
{
	public function accessRules()
	{
		return array(
				/*array('allow', // allow authenticated users to access all actions
						'users'=>array('*'),
				),*/
				array('allow'),
		);
	}
		
	public function actionIndex()
	{
		echo "test";
	}

	public function actionEventInfo($ext_code,$username=null,$password=null,$directLink=false)
	{
	  //  http://127.0.0.1/evserv/WebImageAccess/EventInfo?ext_code=55&username=p.treu&password=q
	  //  http://127.0.0.1/evserv/WebImageAccess/EventImage?ext_code=55&username=p.treu&password=q
	  
	  if ( ($username === null) || ($password === null) )
	  {
	    if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))
	    {
	      $username=$_SERVER['PHP_AUTH_USER'];
	      $password=$_SERVER['PHP_AUTH_PW'];   
	    }
	  }

	  $auth = new UserIdentity($username, $password);
	  if(!$auth->authenticate())
	  {
	    header("WWW-Authenticate: Basic realm=\"Event Server\"");
	    access_denied_check(null,true);
	    return;
	  }
	  	  
        $strPath = $this->relativePathFromExtCode($ext_code);
		
		$strPath =  Yii::app()->params['webImageAccess']['BaseFolder'].$strPath;
	
		$elemet = simplexml_load_file($strPath."eventData.xml");
		
		$linkParams = array();
		
		$linkParams["ext_code"] = $ext_code;
		if($directLink)
		{
		  $linkParams["username"] = $username;
		  $linkParams["password"] = $password;
		}
		
		$linkUrl = Yii::app()->createAbsoluteUrl('WebImageAccess/EventImage', $linkParams);
		$elemet->link = $linkUrl;//vale come $elemet->addChild('link',$linkUrl);

		header("Content-Type: text/xml");
		
		echo $elemet->asXML();
	}

	public function actionEventImage($ext_code,$username=null,$password=null)
	{
	
	  if ( ($username === null) || ($password === null) )
	  {
	    if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))
	    {
	      $username=$_SERVER['PHP_AUTH_USER'];
	      $password=$_SERVER['PHP_AUTH_PW'];   
	    }
	  }

	  $auth = new UserIdentity($username, $password);
	  if(!$auth->authenticate())
	  {
	    header("WWW-Authenticate: Basic realm=\"Event Server\"");
	    access_denied_check(null,true);
	  }
	  	  
		$strPath = $this->relativePathFromExtCode($ext_code);
	
		$strPath =  Yii::app()->params['webImageAccess']['BaseFolder'].$strPath;
	
		$xmlPath = $strPath."eventData.xml";
		
		$elemet = simplexml_load_file($xmlPath);
	
		$plates = $elemet->xpath("/event_info/plate");
	
		$plate = $plates[0];
	
		$imagePath = $strPath . $plate . "_image.jpg";
		$croppedImagePath = $strPath . $plate . "_crop.jpg";
	
		$croppedImageOk = FALSE;
		$jpg = new JpgImage();
		$jpg->load($imagePath);

		header("Content-Type: image/jpg");
		
		//if(!file_exists($croppedImagePath)) // comment to disable cache		
		{
			$jpgtool = new JPGTools($imagePath);
	
			$XmlArray = $jpgtool->readKriaInfo();

			if($XmlArray !== FALSE)
			{
				$plateX      = -1;
				$plateY      = -1;
				$plateWidth  = -1;
				$plateHeight = -1;
					
				if(array_key_exists("PlateMinX", $XmlArray) && 	array_key_exists("PlateMaxX", $XmlArray) && array_key_exists("PlateMinY", $XmlArray) && array_key_exists("PlateMaxY", $XmlArray))
				{
					if($XmlArray["PlateMinX"] < $XmlArray["PlateMaxX"] && $XmlArray["PlateMinY"] < $XmlArray["PlateMaxY"])
					{
						$plateX      = $XmlArray["PlateMinX"];
						$plateY      = $XmlArray["PlateMinY"];
						$plateWidth  = $XmlArray["PlateMaxX"] - $plateX;
						$plateHeight = $XmlArray["PlateMaxY"] - $plateY;
					}
				}
					
				if(array_key_exists("PlateLeft", $XmlArray) && 	array_key_exists("PlateRight", $XmlArray) && array_key_exists("PlateTop", $XmlArray) && array_key_exists("PlateBottom", $XmlArray))
				{
					if($XmlArray["PlateLeft"] < $XmlArray["PlateRight"] && $XmlArray["PlateTop"] < $XmlArray["PlateBottom"])
					{
						$plateX      = $XmlArray["PlateLeft"];
						$plateY      = $XmlArray["PlateTop"];
						$plateWidth  = $XmlArray["PlateRight"] - $plateX;
						$plateHeight = $XmlArray["PlateBottom"] - $plateY;
					}
				}
					
				if($plateX > 0 && $plateY > 0 && $plateWidth > 0 && $plateHeight > 0)
				{
					// params
					$wiap = Yii::app()->params['webImageAccess'];

					// carico i parametri di crop
					$defTopMar = Yii::app()->params['webImageAccess']['defaultTopMargin'];
					$defBtmMar = Yii::app()->params['webImageAccess']['defaultBottomMargin'];
					$defLftMar = Yii::app()->params['webImageAccess']['defaultLeftMargin'];
					$defRgtMar = Yii::app()->params['webImageAccess']['defaultRightMargin'];
	
					// controllo che non escano dall'immagine originale
					$defTopMar = $jpg->legalizeY($defTopMar);
					$defBtmMar = $jpg->legalizeY($defBtmMar);
					$defLftMar = $jpg->legalizeX($defLftMar);
					$defRgtMar = $jpg->legalizeX($defRgtMar);
					$defBndSiz = $jpg->legalizeY($defBndSiz);

					// creo i parametri di crop e controllo che non escano dall'immagine originale
					$cropX = $jpg->legalizeX($plateX - $defLftMar);
					$cropY = $jpg->legalizeY($plateY - $defTopMar);
					$cropWidth  = $jpg->legalizeWidth($cropX, $plateWidth + $defLftMar + $defRgtMar);
					$cropHeight = $jpg->legalizeHeight($cropY, $plateHeight + $defTopMar + $defBtmMar);

					// taglio la banda, se coinvolta
					if(($cropY + $cropHeight) > ($jpg->height() - $defBndSiz))
					{
						$banda = ($cropY + $cropHeight) - ($jpg->height() - $defBndSiz);
						$cropHeight = $cropHeight - $banda;
					}
						
					// croppo
					$croppedImage = $jpg->crop($cropX, $cropY, $cropWidth, $cropHeight);
					if($croppedImage)
						if($croppedImage->output())
						$cropOk = TRUE;
				}			
			}
		}
	
		if(!$croppedImageOk)
			$jpg->output();				
	}

	public function relativePathFromExtCode($ext_code)
	{
		$ext_code = str_pad($ext_code, 12, "0", STR_PAD_LEFT);
		$strPath = str_split($ext_code, 2);
		$strFullPath = "";
		
		foreach($strPath as $ptPiece)
			$strFullPath .= $ptPiece."/";
			
		return $strFullPath;		
		
	}
}