<?php

/**
 *
 * @author p6
 * @property int ID
 * @property int EventID
 * @property string BlobData
 * @property int BlobDataLength
 * @property string epoch
 * @property string type
 * @property int BlobID
 * @property int BlobIDSelected
 * @property string Description
 * @property string FullTime
 * @property string BlobFileName
 * @property string extrainfo
 *
 * @property Rectangle plateRectangle
 * @property photo MediaAttachment
 *
 */
class MediaAttachment extends ActiveRecord
{
  // fields for media attachment proxy - BEGIN
  public $isVehicleTrace = false;
  // fields for media attachment proxy - END

  const BID_M_BW_SPEED_FIRST = 1000;
  public $significantPhotoBlobIdBw = self::BID_M_BW_SPEED_FIRST;
  const BID_M_COL_SPEED_FIRST = 3000;
  public $significantPhotoBlobIdCol = self::BID_M_COL_SPEED_FIRST;
  
  public $significantPhotoColumn = "BlobID";
  
  /**
   *
   * @param system $className
   * @return MediaAttachment
   */
  public static function model($className=__CLASS__)
  {
    return parent::model($className);
  }

  public function tableName()
  {
    return 'teb_table';
  }

  public function defaultScope()
  {
    $alias = $this->getTableAlias(false, false);

   
   return $alias == 't' ? array(
        'condition' => "$alias.BlobID NOT BETWEEN 2000 AND 2999",
    ) : array();
  }

  public function scopes()
  {
    return array(
        'photo' => array('condition' => 'type = "image/jpeg" or type = "JPEG" and BlobID != 4000'),
        'video' => array('condition' => 'type = "AVI/MJPEG" or type = "MP4/H264"'),
        'video_col' => array('condition' => '(type = "AVI/MJPEG" or type = "MP4/H264") AND BlobId=10000'),
        'video_bw' => array('condition' => '(type = "AVI/MJPEG" or type = "MP4/H264") AND BlobId=10001'),
        'preview' => array('condition' => $this->significantPhotoColumn.' = :id', 'params' => array(':id' => $this->significantPhotoBlobIdBw)),
        'previewColor' => array('condition' => $this->significantPhotoColumn.' = :id', 'params' => array(':id' => $this->significantPhotoBlobIdCol)),
    	'extraCameraPhotos' => array('condition' => 'BlobId >= 5000 and BlobId < 6000'),
    );
  }

  /**
   * 
   * @return string
   */
  public function getUrlEnhanced()
  {
    return $this->getUrl(true);
  }

  /**
   *
   * @param boolean $enhanced=false
   * @return string
   */
  public function getUrl($enhanced=false)
  {
    $getBase = $this->isVehicleTrace ? '/media/getVT' : '/media/get';
    $params = array();
    $params['id'] = $this->isVehicleTrace ? $this->EventID : $this->ID;
    if($this->isVehicleTrace)
      $params['type'] = $this->BlobID == 1000 ? 'bw' : 'col';
    if($enhanced)
     	$params['enhanced'] = true;

    return Yii::app()->createUrl($getBase, $params);
     
    //	$url = 	Yii::app()->getRequest()->getHostInfo();
    //	return $url.Yii::app()->params['photoBaseUrl']."/".$this->BlobFileName;
  }

  /**
   * to be used before calling the scope preview
   * @param integer $blobId
   * @return MediaAttachment
   */
  public function setSignificantPhotoBlobIdBw($blobId)
  {
    $this->significantPhotoBlobIdBw = $blobId;
    return $this;
  }

  /**
   * to be used before calling the scope previewColor
   * @param integer $blobId
   * @return MediaAttachment
   */
  public function setSignificantPhotoBlobIdCol($blobId)
  {
    $this->significantPhotoBlobIdCol = $blobId;
    return $this;
  }

  /**
   * to be used before calling the scope preview and previewColor
   * @param string $column default 'BlobID'
   * @return MediaAttachment
   */
  public function setSignificantPhotoColumn($column = 'BlobID')
  {
    $this->significantPhotoColumn = $column;
    return $this;
  }
  
  /**
   * 
   * @param boolean $enhanced=false
   * @return string
   */
  public function getAUrl($enhanced=false)
  {
    $getBase = $this->isVehicleTrace ? '/media/getVT' : '/media/get';
    $params = array();
    $params['id'] = $this->isVehicleTrace ? $this->EventID : $this->ID;
    if($this->isVehicleTrace)
      $params['type'] = $this->BlobID == 1000 ? 'bw' : 'col';
    if($enhanced)
     	$params['enhanced'] = true;

    return Yii::app()->createAbsoluteUrl($getBase, $params);

    //	$url = 	Yii::app()->getRequest()->getHostInfo();
    //	return $url.Yii::app()->params['photoBaseUrl']."/".$this->BlobFileName;
  }

  /**
   *
   * @return string
   */
  public function getBaseUrl()
  {
    $url = 	Yii::app()->getRequest()->getHostInfo();
    return $url.Yii::app()->params['photoBaseUrl']."/".$this->BlobFileName;
  }

  /**
   *
   * @return string
   */
  public function getPath()
  {
    $basePath = Yii::app()->params['photoBasePath'];
    $filename = $this->BlobFileName;
    return pathCombine($basePath,$filename);
  }

  /**
   * return $this->type == 'image/jpeg';
   * @return boolean
   */
  public function isPhoto()
  {
    return $this->type == 'image/jpeg';
  }

  /**
   * return $this->isPhoto() && $this->BlobID < 4000;
   * @return boolean
   */
  public function hasFooter()
  {
    return $this->isPhoto() && $this->BlobID < 4000;
  }

  /**
   * return (($this->type == 'AVI/MJPEG') || ($this->type == 'MP4/H264'));
   * @return boolean
   */
  public function isVideo()
  {
    return (($this->type == 'AVI/MJPEG') || ($this->type == 'MP4/H264'));
  }

  /**
   *
   * @return Rectangle
   */
  public function getFooterRectangle()
  {
    if ($this->hasFooter())
    {
      $topLeft = new Coordinate(0, $this->getHeight() - 48);
      $bottomRight = new Coordinate($this->getWidth(), $this->getHeight());
      $rectangle = new Rectangle($topLeft, $bottomRight);
      return $rectangle;
    }
  }

  /**
   *
   * @return Rectangle
   */
  public function getPlateRectangle()
  {
    //logLine("media::getplaterect(isPhoto="._2str($this->isPhoto()).",hasXml="._2str($this->hasXml()).")");
    if ($this->isPhoto() && $this->hasXml())
    {
      $parser = MediaAttachmentParserProxy::getParser($this);
      if ($parser->hasRectangle())
        return $parser->getRectangle();
    }
  }

  /**
   *
   * @return Rectangle[]
   */
  public function getExtraAreas()
  {
    if ($this->isPhoto() && $this->hasXml())
    {
      $parser = MediaAttachmentParserProxy::getParser($this);
      return $parser->getExtraAreas();
    }
    return array();
  }

  /**
   * @return SimpleXMLElement|NULL
   */
  public function getXml()
  {
    if($this->hasXml())
    {
      return new SimpleXMLElement($this->extrainfo);
    }
    return null;
  }

  /**
   *
   * @return number
   */
  public function getWidth()
  {
    $sizes = $this->getAttachmentSize();
    if (isset($sizes))
      return $sizes[0];

  }

  /**
   *
   * @return number
   */
  public function getHeight()
  {
    $sizes = $this->getAttachmentSize();

    if (isset($sizes))
      return $sizes[1];
  }

  /**
   *
   * @param array $eventIds
   * @return MediaAttachment
   */
  public function byEventIds($eventIds)
  {
    if(!is_array($eventIds))
      $eventIds = array($eventIds);

    $this->getDbCriteria()->addInCondition('EventID', $eventIds);

    return $this;
  }


  /**
   *
   * @return MediaAttachment
   */
  public function byPhotoReport()
  {
    $this->getDbCriteria()->addInCondition('BlobID', array(MediaAttachment::BID_M_BW_SPEED_FIRST));

    return $this;
  }

  /**
   *
   * @return array
   */
  private function getAttachmentSize()
  {
    if ($this->isPhoto())
    {
      $size =  getimagesize($this->getFinalSearchPath());

      return $size;
    }
  }

  /**
   * return (isset($this->extrainfo) && (strlen($this->extrainfo) > 0));
   * @return boolean
   */
  public function hasXml()
  {
    return (isset($this->extrainfo) && (strlen($this->extrainfo) > 0));
  }

  /**
   * trova la path locale o url per leggere il file da PHP!
   * @return string
   */
  public function getFinalSearchPath()
  {
    if(paramdeep('photoBaseLocationByUrl'))
      $filename = YII_DEBUG ? resolve_redirect($this->baseUrl) : $this->baseUrl;
    else
      $filename = $this->path;
    return $filename;
  }

}
