<?php

class MediaController extends Controller
{
  public function filters()
  {
    return array(
        array('application.filters.SyslogFilter',),
    );
  }

  public function actionGetVT($id, $type)
  {
    $model = VehicleTrace::model()->findByPk($id);
    if($model===null)
      throw new CHttpException(404,'The requested media does not exist.');

    $enhanced = $_REQUEST['enhanced'];
     
    $medias = $model->getMediaAttachments();
    if(isset($medias[$type]))
      self::outputMedia($medias[$type], $enhanced);
    else
      throw new CHttpException(404,'The requested media does not exist.');
  }

  public function actionGet($id)
  {
    $media = $this->loadModel($id);
    $enhanced = $_REQUEST['enhanced'];
    self::outputMedia($media, $enhanced);
  }

  /**
   * send to the output stream a MediaAttachment and call exit
   * @param MediaAttachment $media
   * @param bool $enhanced
   */
  public static function outputMedia(MediaAttachment $media, $enhanced)
  {
    $filename = $media->getFinalSearchPath();
    
    if(!paramdeep('media','enableEnhancedMode'))
      $enhanced = false;

    //Yii::trace("get media file: $filename");

    if($media->isVideo())
    {
      if(!Yii::app()->user->checkAccess('media_view_video'))
      {
        header('Content-Type: image/png');
        readfile(access_denied_png_url());
        exit;
      }
       
      if(startsWithAny($filename, array("http://","https://"), false))
      {
        header('Content-Type: video/mp4');        
        readfile($filename);
      }
      else
      {
        get_file_stream($filename,'video/mp4',true,true);
      }
      exit;
    }

    if(!$media->isPhoto())
    {
      throw new CHttpException(500,"Unknown media type '$media->type'");
    }
     
    if(!Yii::app()->user->checkAccess('media_view_photo'))
    {
      header('Content-Type: image/png');
      readfile(access_denied_png_url());
      exit;
    }

    if(Yii::app()->user->checkAccess('license_plate_visibility') && Yii::app()->user->checkAccess('other_vehicles_license_plate_visibility') && Yii::app()->user->checkAccess('event_date_time_locality_visibility') && !$enhanced)
    {
      header('Content-Type: image/jpeg');
      readfile($filename);
      exit;
    }

    //logLine("apply FILE privacy [$filename]");
    $img = imagecreatefromjpeg($filename);
    
    $plateFix = paramdeep('media','plateRectFix');    
    $plateRect = $media->plateRectangle;
    $areas = $media->getExtraAreas();
    $hiddenAreas = array();

    // posso vedere la targa dell'evento?
    if(!Yii::app()->user->checkAccess('license_plate_visibility'))
    {
      if(isset($areas) && isset($areas['extended_plate_area']))
        $plateRect = $areas['extended_plate_area'];

      if($plateRect instanceof Rectangle)
      {
        //logLine("apply PLATE privacy ["._2str($plateRect)."]");
        $hiddenAreas[] = (string)$plateRect;

        $cropped = imagecreatetruecolor($plateRect->width, $plateRect->height);
         
        imagecopy($cropped, $img, 0, 0, $plateRect->topLeft->x, $plateRect->topLeft->y, $plateRect->width, $plateRect->height);
         
        imagefilter($cropped, IMG_FILTER_PIXELATE, 10);
         
        imagecopy($img, $cropped, $plateRect->topLeft->x, $plateRect->topLeft->y, 0, 0,  $plateRect->width, $plateRect->height);
         
        imagedestroy($cropped);
      }
    }
    else if($enhanced)
    {
      $RGB = ImageAreaHelper::getAreaColorRGB('extended_plate_area');
      $color = imagecolorallocate($img, $RGB['R'], $RGB['G'], $RGB['B']);
      $rectOriginal = $areas['extended_plate_area'];
  
      if($rectOriginal instanceof Rectangle)
      {
        // fix plate rect?
        $rect = Rectangle::applyFix($rectOriginal, $plateFix);
        // end up fixin'
        imagerectangle($img, $rect->topLeft->x, $rect->topLeft->y, $rect->BottomRight->x, $rect->BottomRight->y, $color);
      }
    }

    // posso vedere le altre targhe?
    if(!Yii::app()->user->checkAccess('other_vehicles_license_plate_visibility'))
    {
      if(isset($areas))
      {
        if(isset($areas['other_plates']))
        {
          $otherPlates = $areas['other_plates'];

          foreach($otherPlates as $area)
          {
            if(array_value_exists($hiddenAreas, (string)$area))
              continue;

            $hiddenAreas[] = (string)$area;

            $cropped = imagecreatetruecolor($area->width, $area->height);

            imagecopy($cropped, $img, 0, 0, $area->topLeft->x, $area->topLeft->y, $area->width, $area->height);
             
            imagefilter($cropped, IMG_FILTER_PIXELATE, 10);
             
            imagecopy($img, $cropped, $area->topLeft->x, $area->topLeft->y, 0, 0,  $area->width, $area->height);
             
            imagedestroy($cropped);
          }
        }
      }
    }
    else if($enhanced)
    {
      if(isset($areas))
      {
        if(isset($areas['other_plates']))
        {
          $RGB = ImageAreaHelper::getAreaColorRGB('other_plates');
          $color = imagecolorallocate($img, $RGB['R'], $RGB['G'], $RGB['B']);
          $otherPlates = $areas['other_plates'];
          foreach($otherPlates as $rectOriginal)
          if($rectOriginal instanceof Rectangle)
          {
            // fix plate rect?
            $rect = Rectangle::applyFix($rectOriginal, $plateFix);
            // end up fixin'
            
            imagerectangle($img, $rect->topLeft->x, $rect->topLeft->y, $rect->BottomRight->x, $rect->BottomRight->y, $color);
          }
        }
      }
    }

    // posso vedere il footer?
    if(!Yii::app()->user->checkAccess('event_date_time_locality_visibility') && $media->hasFooter())
    {
      // rimuovi footer (pixelate)
      $area = $media->footerRectangle;

      if(isset($area))
      {
        $cropped = imagecreatetruecolor($area->width, $area->height);
         
        imagecopy($cropped, $img, 0, 0, $area->topLeft->x, $area->topLeft->y, $area->width, $area->height);

        imagefilter($cropped, IMG_FILTER_PIXELATE, 10);

        imagecopy($img, $cropped, $area->topLeft->x, $area->topLeft->y, 0, 0,  $area->width, $area->height);

        imagedestroy($cropped);
      }
    }

    // tutte i bordi che mancano
    $colorAnyting = imagecolorallocate($img, 255, 0, 0);
    foreach($areas as $eak => $ea)
    {
      if($eak != 'extended_plate_area' && $eak != 'other_plates')
      {
        // se è un sottoarray
        if(is_array($ea))
        {
          // per ogni sotto elemento
          foreach($ea as $seak => $sea)
          if($sea instanceof Rectangle)
          {
            // è da nascondere? skip
            if(array_value_exists($hiddenAreas, (string)$sea))
              continue;
            //logLine("$id=$eak($seak)");
            $sea = Rectangle::applyFix($sea, $plateFix);
            imagerectangle($img, $sea->topLeft->x, $sea->topLeft->y, $sea->BottomRight->x, $sea->BottomRight->y, $colorAnyting);
            $sea1 = $sea->getOuterRect();
            imagerectangle($img, $sea1->topLeft->x, $sea1->topLeft->y, $sea1->BottomRight->x, $sea1->BottomRight->y, $colorAnyting);
          }
        }
        elseif($ea instanceof Rectangle)
          // è un singolo elemento
        {
          // è da nascondere? skip
          if(array_value_exists($hiddenAreas, (string)$ea))
            continue;
          //logLine("$id=$eak");
          $ea = Rectangle::applyFix($ea, $plateFix);
          imagerectangle($img, $ea->topLeft->x, $ea->topLeft->y, $ea->BottomRight->x, $ea->BottomRight->y, $colorAnyting);          
          $ea1 = $ea->getOuterRect();
          imagerectangle($img, $ea1->topLeft->x, $ea1->topLeft->y, $ea1->BottomRight->x, $ea1->BottomRight->y, $colorAnyting);
        }
      }
    }
    ///////////////////////////////////////
     
    header('Content-Type: image/jpeg');
     
    imagejpeg($img, NULL, 75);
     
    imagedestroy($img);

    exit;
  }

  /**
   *
   * @param mixed $id
   * @throws CHttpException
   * @return MediaAttachment
   */
  public function loadModel($id)
  {
    $model=MediaAttachment::model()->findByPk($id);
    if($model===null)
      throw new CHttpException(404,'The requested media does not exist.');
     
    return $model;
  }
}