<?php

/**
 * This is the model class for table "vehicletracetable".
 *
 * The followings are the available columns in table 'vehicletracetable':
 * @property string $ID
 * @property string $VehicleID
 * @property string $VehicleUUID
 * @property double $Speed
 * @property double $MeanSpeed
 * @property double $Height
 * @property double $Width
 * @property double $Length
 * @property string $LaneID
 * @property string $IsBoxComputed
 * @property double $DetectionLength
 * @property double $MinimumCameraDistance
 * @property double $MaximumCameraDistance
 * @property string $StartDateTime
 * @property string $StartDate
 * @property string $StartTime
 * @property string $FullStartTime
 * @property string $EndDateTime
 * @property string $EndDate
 * @property string $EndTime
 * @property string $FullEndTime
 * @property double $InterDistance
 * @property string $ClassName
 * @property string $KemlerCode
 * @property string $Color
 * @property double $Brightness
 * @property string $Direction
 * @property string $WorkingMode
 * @property string $GateID
 * @property string $Epoch
 * @property string $ImageBN
 * @property string $ImageBNLength
 * @property string $ImageBNTick
 * @property string $ImageBNExtraInfo
 * @property string $ImageCOL
 * @property string $ImageCOLLength
 * @property string $ImageCOLTick
 * @property string $ImageCOLExtraInfo
 * @property string $BlobFileNameBN
 * @property string $BlobFileNameCOL
 * @property string $Nationality
 * @property string $NetworkID
 * @property string $id_vehicle_color
 * @property string $speed_limit_signs
 * @property string $truck_bar_type
 * @property string $custom_vehicle_type
 * @property string $custom_nationality
 * @property integer $plate_to_be_checked
 * @property string $video_file_name
 * 
 * @property Bookmark bookmark
 * @property VehicleColor colorSet
 * @property Gate gate
 * @property Alert alert
 * 
 */
class VehicleTrace extends ActiveRecord implements IBookmarkObject, IVehicleEvent
{

  // fields for the admin search - BEGIN
  public $searchColor = null;
  public $searchBookmarked = false;
  // fields for the admin search - END

  public static function model($className=__CLASS__)
  {
    return parent::model($className);
  }

  public $event_date_start;
  public $event_date_end;

  public $kemlerSearchString;

  public $search_speed_start;
  public $search_speed_end;


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

  public function rules()
  {
    return array(
        array('IsBoxComputed', 'required'),
        array('Speed, MeanSpeed, Height, Width, Length, DetectionLength, MinimumCameraDistance, MaximumCameraDistance, InterDistance, Brightness', 'numerical'),
        array('VehicleID, VehicleUUID, FullStartTime, FullEndTime, ClassName, KemlerCode, Color, Direction, WorkingMode, ImageBNTick, ImageBNExtraInfo, ImageCOLTick, ImageCOLExtraInfo, BlobFileNameBN, BlobFileNameCOL, Nationality', 'length', 'max'=>250),
        array('LaneID, IsBoxComputed, GateID, ImageBNLength, ImageCOLLength, NetworkID, id_vehicle_color', 'length', 'max'=>20),
        array('custom_nationality, custom_vehicle_type, StartDateTime, StartDate, StartTime, EndDateTime, EndDate, EndTime, Epoch, ImageBN, ImageCOL, video_file_name', 'safe'),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array('ID, VehicleID, VehicleUUID, Speed, MeanSpeed, Height, Width, Length, LaneID, IsBoxComputed, DetectionLength, MinimumCameraDistance, MaximumCameraDistance, StartDateTime, StartDate, StartTime, FullStartTime, EndDateTime, EndDate, EndTime, FullEndTime, InterDistance, ClassName, KemlerCode, Color, Brightness, Direction, WorkingMode, GateID, Epoch, ImageBN, ImageBNLength, ImageBNTick, ImageBNExtraInfo, ImageCOL, ImageCOLLength, ImageCOLTick, ImageCOLExtraInfo, BlobFileNameBN, BlobFileNameCOL, Nationality, NetworkID, id_vehicle_color, event_date_start, event_date_end, kemlerSearchString, search_speed_start, search_speed_end, video_file_name', 'safe', 'on'=>'search'),
    );
  }

  public function relations()
  {
    return array(
        'bookmark'							=> array(self::HAS_ONE,  'Bookmark' ,  'id_reference', 'condition'=>"bookmark.type='vehicletrace' AND id_user=".user()->id),
        'colorSet' => array(self::BELONGS_TO , 'VehicleColor' , 'id_vehicle_color'),
        'gate'    => array(self::BELONGS_TO , 'Gate' , array('GateID'      => 'Gate')),
        'alert'    => array(self::BELONGS_TO , 'Alert' , array('VehicleUUID'      => 'event_uuid')),
    );
  }

  public function behaviors()
  {
    return array('edatetimebehavior' => array('class' => 'ext.EDateTimeBehavior'));
  }
  public function myAttributeLabels()
  {
    return array(
        'VehicleID' => t('Plate'),
        'StartDate' => t('Date'),
        'StartTime' => t('Time'),
        'GateID'    => t('Gate'),
        'LaneID'    => t('Lane'),
        'ClassName' => t('Class'),
        'Nationality' => t('Country'),
        'LaneID'        => t('Lane'),
        'Speed'       => t('Km/h'),
        'kemlerSearchString'  => t('Kemler'),
        'alert'  			=> t('Alert'),
    );
  }

  public function search()
  {
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('ID',$this->ID);
    //  $criteria->compare('VehicleID',$this->VehicleID,true);
    if(!empty($this->VehicleID))
      $criteria->addCondition("MATCH(VehicleID) AGAINST('*".$this->VehicleID."*' IN BOOLEAN MODE)");

    $criteria->compare('StartDateTime',$this->StartDateTime,true);


    if(empty($this->ClassName))
      $criteria->compare('ClassName',$this->ClassName);
    else
    {
      $conditionVClass = "custom_vehicle_type = '".$this->ClassName."' OR (custom_vehicle_type is null AND ClassName = '".$this->ClassName."')";
      $criteria->addCondition($conditionVClass);
    }


    if($this->searchBookmarked)
    {
      $this->withBookmark($criteria);
    }

    $criteria->compare('GateID',$this->GateID);

    // kemler
    $kemlerStr = $this->kemlerSearchString;
    if($kemlerStr == "*")
    {
      $criteria->addCondition("(KemlerCode is not null AND KemlerCode != '')");
    }
    else
    {
      $kemlerStr = str_replace("-", "", $kemlerStr);
      $criteria->compare('KemlerCode', $kemlerStr,true);
    }

    $criteria->compare('LaneID',$this->LaneID,true);

    if(!empty($this->Nationality))
      $criteria->addInCondition('Nationality', PlateCountry::getPossibleTag($this->Nationality));

    if(!empty($this->event_date_start))
    {
      $theStartTime = DateTime::createFromFormat(Yii::app()->params['datetimeselect_format'][Yii::app()->language]['php'], $this->event_date_start);
      $startDT = DateHelper::formatISO9075DateTime($theStartTime);

      $criteria->addCondition("StartDateTime >= '$startDT'");
    }

    if(!empty($this->event_date_end))
    {
      $theEndTime = DateTime::createFromFormat(Yii::app()->params['datetimeselect_format'][Yii::app()->language]['php'], $this->event_date_end);
      $endDT = DateHelper::formatISO9075DateTime($theEndTime);

      $criteria->addCondition("StartDateTime <= '$endDT'");  // date is database date column field
    }


    if(!empty($this->search_speed_start) && empty($this->search_speed_end))
    {
      $criteria->addCondition("Speed >= '$this->search_speed_start'");  // date is database date column field

    }elseif(!empty($this->search_speed_end) && empty($this->search_speed_start))
    {
      $criteria->addCondition("Speed <= '$this->search_speed_end'");
    }elseif(!empty($this->search_speed_end) && !empty($this->search_speed_start))
    {
      $criteria->addCondition("Speed  >= '$this->search_speed_start' and Speed <= '$this->search_speed_end'");
    }

    $criteria->order = 'StartDateTime asc';

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'pagination'=>array(
            'pageSize'=>15,
        ),
    ));
  }

  public function getVehicleSpeed()
  {
    return $this->Speed;
  }

  public function getKemlerCode()
  {
    $Kem = $this->getAttribute('KemlerCode');

    if(strlen($Kem) <= 0)
      return '';

    $pos = strrpos($Kem, ";");
    if ($pos === false)
    {
      $pos = strrpos($Kem, "-");
      if ($pos === false)
      {
        $offset = strlen($Kem) - 4;
        $part1 = substr($Kem, 0, $offset);
        $part2 = substr($Kem, $offset);

        $part1 = $part1 . "-";
        $whole = $part1 . $part2;

        return $whole;
      }
    }
    return str_replace(';', '-', $Kem);
  }


  public function getKemler()
  {
    return $this->KemlerCode;
  }

  public function getPlate()
  {
    return $this->VehicleID;
  }

  public function getSpeed()
  {
    return number_format($this->attributes['Speed'], 2);
  }

  public function getPreviewPhotoUrl()
  {
    if(!Yii::app()->user->checkAccess('media_view_photo'))
      return access_denied_png_url();
    
    $medias = $this->getMediaAttachments();
    if(isset($medias['bw']))
    	return $medias['bw']->getAUrl();
        
    /*
    $url = 	Yii::app()->getRequest()->getHostInfo();
    return $url .Yii::app()->params['photoBaseUrl']."/".$this->BlobFileNameBN;
    */
  }
  public function getPreviewColorPhotoUrl()
  {
    if(!Yii::app()->user->checkAccess('media_view_photo'))
      return access_denied_png_url();
    
    //logLine("$this->ID before");
    $medias = $this->getMediaAttachments();
    //logLine("$this->ID after ".count($medias));
    if(isset($medias['col']))
      return $medias['col']->getAUrl();
    /*
    $url = 	Yii::app()->getRequest()->getHostInfo();
    return $url .Yii::app()->params['photoBaseUrl']."/".$this->BlobFileNameCOL;
    */
  }

  public function getNationalityCode()
  {
    $kriaPlate = PlateCountry::model()->findByAttributes(array('label' => $this->Nationality));
    if (isset($kriaPlate))
      return $kriaPlate->iso_code;
  }
  public function getVehicleClass()
  {
    return VehicleTypes::getFromDeviceClass($this->ClassName);
  }
  public function getEventDateTime()
  {
    return $this->StartDateTime;
  }

  public function getGateLabel()
  {
    return $this->gate->Descrizione;
  }
  public function getGateShortLabel()
  {
    return $this->gate->short_name;
  }
  public function getCustom_nationality()
  {
    $custom_nationality = $this->getAttribute('custom_nationality');
    if (isset($custom_nationality) && $custom_nationality != '')
      return $custom_nationality;
    else {
      $kriaPlate = PlateCountry::model()->findByAttributes(array('label' => $this->Nationality));
      if (isset($kriaPlate))
        return $kriaPlate->iso_code;
    }
  }

  public function getCustom_vehicle_type()
  {
    $custom_vehicle_type = $this->getAttribute('custom_vehicle_type');
    $kria_vehicle_type = $this->getAttribute('ClassName');
    if (isset($custom_vehicle_type) && $custom_vehicle_type != '')
      return $custom_vehicle_type;
    else
      return VehicleTypes::getFromDeviceClass($kria_vehicle_type);
    //     return $kria_vehicle_type;
  }


  public function getSpeedLimitSignList()
  {
    if(is_null($this->speed_limit_signs) || strlen($this->speed_limit_signs) <= 0)
      return null;


    $signs = explode(';', $this->speed_limit_signs);

    sort($signs, SORT_NUMERIC);

    return $signs;
  }

  static public function getNationCodesList()
  {
    $vTrace = VehicleTrace::model()->findAll(array('select'=>'Nationality', 'distinct'=> true));
    if(is_null($vTrace))
      return null;

    $arr = array();
    if(!is_array($vTrace))
      $vTrace = array($vTrace);

    $labels = array();

    foreach($vTrace as $vT)
      $labels[] = $vT->Nationality;

    return PlateCountry::getNationListFromLabels($labels);
  }

  public function getPhotosUrl()
  {
    /*
    $photos = array();

    if(!empty($this->BlobFileNameBN))
      $photos[] = $this->BlobFileNameBN;
    if(!empty($this->BlobFileNameCOL))
      $photos[] = $this->BlobFileNameCOL;

    return array_map(function($photo) {
      return Yii::app()->params['photoBaseUrl'].'/'.$photo;
    }, $photos);
    */
    //return array_map(function($photo) { return url(Yii::app()->params['photoBaseUrl'].'/'.$photo); }, $photos);
    $medias = $this->getMediaAttachments();
    $photos = array();
    foreach($medias as $m)
    	$photos[] = $m->getUrl();
    return $photos;    
  }

  public function getPhotosAUrl()
  {
    /*    
    $photos = array();

    if(!empty($this->BlobFileNameBN))
      $photos[] = $this->BlobFileNameBN;
    if(!empty($this->BlobFileNameCOL))
      $photos[] = $this->BlobFileNameCOL;

    return array_map(function($photo) {
      return Yii::app()->getRequest()->getHostInfo().Yii::app()->params['photoBaseUrl'].'/'.$photo;
    }, $photos);
    */
    //return array_map(function($photo) { return absoluteUrl(Yii::app()->params['photoBaseUrl'].'/'.$photo); }, $photos);
    $medias = $this->getMediaAttachments();
    $photos = array();
    foreach($medias as $m)
      $photos[] = $m->getAUrl();
    return $photos;
  }

  public function getVideoUrl()
  {
    if(empty($this->video_file_name))
      return null;
    //return url(Yii::app()->params['photoBaseUrl'].'/'.$this->video_file_name);
    return Yii::app()->params['photoBaseUrl'].'/'.$this->video_file_name;
  }

  public function getVideoAUrl()
  {
    if(empty($this->video_file_name))
      return null;
    //return url(Yii::app()->params['photoBaseUrl'].'/'.$this->video_file_name);
    return Yii::app()->getRequest()->getHostInfo().Yii::app()->params['photoBaseUrl'].'/'.$this->video_file_name;
  }

  public function getYellowBarType()
  {
    //	if(empty($this->truck_bar_type))
    //	return null;
     
    return $this->truck_bar_type;
  }

  public function withBookmark()
  {
    $withCriteria = $this->getDbCriteria()->with[] = 'bookmark';
     
    return $this;
  }

  public function getBookmarkData()
  {
    $a = $this->alert;
    $v = $this;
    $e = null;

    $bd = new CArray();

    $bd->has_alert = $a != null;
    if($a != null)
    {
      $e = $a->event;
      $bd->alert_id = $a->id;
      $bd->alert_book = Bookmark::model()->find("id_user=:usr AND id_reference=:ref AND type=:typ",array(':usr'=>user()->id, ':ref'=>$bd->alert_id, ':typ'=>Bookmark::TYPE_ALERT));
    }

    $bd->has_event = $e != null;
    if($e != null)
    {
      $bd->event_id = $e->ID;
      $bd->event_book = Bookmark::model()->find("id_user=:usr AND id_reference=:ref AND type=:typ",array(':usr'=>user()->id, ':ref'=>$bd->event_id, ':typ'=>Bookmark::TYPE_EVENT));
    }

    $bd->has_trace = $v != null;
    if($v != null)
    {
      $bd->trace_id = $v->ID;
      $bd->trace_book = Bookmark::model()->find("id_user=:usr AND id_reference=:ref AND type=:typ",array(':usr'=>user()->id, ':ref'=>$bd->trace_id, ':typ'=>Bookmark::TYPE_VEHICLE_TRACE));
    }

    $bd->self_id = $this->ID;
    $bd->self_type = Bookmark::TYPE_VEHICLE_TRACE;
    $bd->self_book = $bd->trace_book;

    return $bd;
  }

  /**
   * returns the images as MediaAttachment(s) 
   * @return MediaAttachment[]
   */
  public function getMediaAttachments()
  {
    $mediaAttachments = array();

    if(!empty($this->BlobFileNameBN))
    {
    	$media = new MediaAttachment();
    	
    	$media->isVehicleTrace = true;
    	$media->BlobFileName = $this->BlobFileNameBN;
    	$media->BlobID = 1000;
    	$media->BlobIDSelected = 1000;
    	$media->EventID = $this->ID;
    	$media->type = "image/jpeg";
    	$media->epoch = $this->Epoch;
    	$media->BlobData = null;
    	$media->ID = 0;
    	$media->BlobDataLength = 0;
    	$media->FullTime = $this->Epoch;
    	$media->Description = "VehicleTrace#0";
    	$media->extrainfo = JPGTools::getKriaXml($media->getPath());
    	//if(!$media->hasXml())
      	//$media->extrainfo = JPGTools::getKriaXml($media->getAUrl());
    	
    	$mediaAttachments['bw'] = $media;
    }

    if(!empty($this->BlobFileNameCOL))
    {
    	$media = new MediaAttachment();
    	
    	$media->isVehicleTrace = true;
    	$media->BlobFileName = $this->BlobFileNameCOL;
    	$media->BlobID = 3000;
    	$media->BlobIDSelected = 3000;
    	$media->EventID = $this->ID;
    	$media->type = "image/jpeg";
    	$media->epoch = $this->Epoch;
    	$media->BlobData = null;
    	$media->ID = 0;
    	$media->BlobDataLength = 0;
    	$media->FullTime = $this->Epoch;
    	$media->Description = "VehicleTrace#1";
    	$media->extrainfo = JPGTools::getKriaXml($media->getPath());
    	//if(!$media->hasXml())
      	//$media->extrainfo = JPGTools::getKriaXml($media->getAUrl());
    	 
    	$mediaAttachments['col'] = $media;
    }
    
    return $mediaAttachments;
  }

}
