<?php

/**
 * database 'tebtable'
 * @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 and BlobID NOT BETWEEN 2000 AND 2999)'),
            '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 < 9000'),
        );
    }

    /**
     * 
     * @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();
        }
    }

    /**
     * setPlateRectangleFromDragonImage
     *  Change Plate position. Ng. 11/02/2019 DragonImageObscure mode. Trento Env.
     * @param croppedX
     * @param croppedY
     * @param croppedWidth
     * @param croppedHeight
     * 
     */
    public function setPlateRectangleFromDragonImage($croppedX,$croppedY,$croppedWidth,$croppedHeight) {
        //logLine("media::getplaterect(isPhoto="._2str($this->isPhoto()).",hasXml="._2str($this->hasXml()).")");
        if ($this->isPhoto() && $this->hasXml()) {
            $parser = MediaAttachmentParserProxy::getParser($this);
            if ($parser->hasRectangle()){
                $temp_xml = $this->xml;
                //Yii::log("\t XML ExtraData 003 \t". print_r($this->extrainfo,true)." ", "error", "event.actionDragonImageObscureChangeXML");
                
                $temp_xml->PlateMinX = strval((int) $croppedX);
                $temp_xml->PlateMaxX = strval((int) ($croppedX+$croppedWidth));
                $temp_xml->PlateMinY = strval((int) $croppedY);
                $temp_xml->PlateMaxY = strval((int) ($croppedY+$croppedHeight));

                
                $this->extrainfo = $temp_xml->asXML();
                
                //Yii::log("\t XML ExtraData 003 \t". print_r($this->extrainfo,true)." ", "error", "event.actionDragonImageObscureChangeXML");
                  
               // $this->extrainfo = serialize($this->xml->asXML());
            }
        }
    }
    /**
     *
     * @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;
    }

    public function isSelectable($deviceType) {
        switch ($deviceType) {
            case "section":
                return $this->BlobID >= 5000 && $this->BlobID < 6000 || $this->BlobID == 1000 || $this->BlobID == 1001;
            case "speed":
            case "red":
            case "ztl":
                return $this->BlobID >= 1000 && $this->BlobID < 2000;
            default:
                return false;
        }
    }

    public function isGenerated() {
        //to be generated it must have 7000 < id < 8000 
        return $this->BlobID >= 7000 && $this->BlobID < 9000;
    }

    public function getSectionGroup($deviceType) {
        //1000 -> first device (speed)
        //1001 -> second device (speed)
        //500X -> first device (face)
        //510X -> second device (face)
        //800X -> first device (plate-bw)
        //810X -> second device (plate-bw)
        $group = "none";
        $isFirstFace = $this->BlobID >= 5000 && $this->BlobID < 5100;
        $isSecondFace = $this->BlobID >= 5100 && $this->BlobID < 5200;
        $isFirstBW = $this->BlobID == 1000;
        $isSecondBW = $this->BlobID == 1001;
        $isFirstColor = $this->BlobID == 3000;
        $isSecondColor = $this->BlobID == 3001;
        $isFirstFaceCrop = $this->BlobID >= 7000 && $this->BlobID < 7100;
        $isSecondFaceCrop = $this->BlobID >= 7100 && $this->BlobID < 7200;
        $isFirstPlateCrop = $this->BlobID >= 8000 && $this->BlobID < 8100;
        $isSecondPlateCrop = $this->BlobID >= 8100 && $this->BlobID < 8200;
        switch ($deviceType) {
            case "section":
                if ($isFirstBW || $isFirstColor || $isFirstFace || $isFirstFaceCrop || $isFirstPlateCrop) {
                    $group = "first";
                }
                if ($isSecondBW || $isSecondColor || $isSecondFace || $isSecondFaceCrop || $isSecondPlateCrop) {
                    $group = "second";
                }
                break;
            case "speed":
            case "red":
            case "ztl":
                $group = "first";
                break;
        }
        return $group;
    }

    public function getCroppingType() {
        $croppingType = "none";
        if ($this->BlobID >= 1000 && $this->BlobID < 2000 || $this->BlobID >= 8000 && $this->BlobID < 9000) {
            $croppingType = "plate-bw";
        }
        if ($this->BlobID >= 3000 && $this->BlobID < 4000) {
            $croppingType = "plate-color";
        }
        if ($this->BlobID >= 4000 && $this->BlobID < 5000) {
            $croppingType = "none";
        }
        if ($this->BlobID >= 5000 && $this->BlobID < 6000) {
            $croppingType = "face";
        }
        if ($this->BlobID >= 6000 && $this->BlobID < 7000) {
            $croppingType = "extra";
        }
        if ($this->BlobID >= 7000 && $this->BlobID < 8000) {
            $croppingType = "face";
        }
        return $croppingType;
    }

    public function getSmallDescription($deviceType) {
        //1001 -> first device (speed)
        //1002 -> second device (speed)
        //500X -> first device (face)
        //510X -> second device (face)
        $descriptionToReturn = "";
        switch ($deviceType) {
            case "section":
                if ($this->BlobID >= 1000 && $this->BlobID < 2000) {
                    $descriptionToReturn = (($this->BlobID % 1000 == 0) ? "Section start " : " Section end ") . "B&W shot";
                }
                if ($this->BlobID >= 3000 && $this->BlobID < 4000) {
                    $descriptionToReturn = (($this->BlobID % 3000 == 0) ? "Section start " : "Section end ") . "Color shot";
                }
                if ($this->BlobID >= 5000 && $this->BlobID < 6000) {
                    $descriptionToReturn = (($this->BlobID % 5000 < 100) ? "Section start " : "Section end ") . "Face camera shot #" . ((($this->BlobID % 5000) % 100) + 1);
                }
                if ($this->BlobID >= 6000 && $this->BlobID < 7000) {
                    $descriptionToReturn = "Extra info shot #" . (($this->BlobID % 6000) + 1);
                }
                if ($this->BlobID >= 7000 && $this->BlobID < 8000) {
                    $descriptionToReturn = (($this->BlobID % 7000 < 100) ? "Section start " : "Section end ") . "Face crop";
                }
                if ($this->BlobID >= 8000 && $this->BlobID < 9000) {
                    $descriptionToReturn = (($this->BlobID % 8000 < 100) ? "Section start " : "Section end ") . "Plate crop ";
                }
                break;
            case "speed":
                if ($this->BlobID >= 1000 && $this->BlobID < 2000) {
                    $descriptionToReturn = "B&W shot #" . (($this->BlobID % 1000) + 1) . "-" . $this->BlobID;
                }
                if ($this->BlobID >= 3000 && $this->BlobID < 4000) {
                    $descriptionToReturn = "Color shot #" . (($this->BlobID % 3000) + 1) . "-" . $this->BlobID;
                }
                if ($this->BlobID >= 5000 && $this->BlobID < 6000) {
                    $descriptionToReturn = "Face camera shot #" . (($this->BlobID % 5000) + 1) . "-" . $this->BlobID;
                }
                if ($this->BlobID >= 6000 && $this->BlobID < 7000) {
                    $descriptionToReturn = "Extra info shot #" . (($this->BlobID % 6000) + 1) . "-" . $this->BlobID;
                }
                if ($this->BlobID >= 7000 && $this->BlobID < 8000) {
                    $descriptionToReturn = "Face crop";
                }
                if ($this->BlobID >= 8000 && $this->BlobID < 9000) {
                    $descriptionToReturn = "Plate crop";
                }
                break;

            case "red":
            case "ztl":
                $descriptionToReturn = "";
                break;
        }
        if (($this->BlobID >= 5000 && $this->BlobID < 5100) || $this->BlobID == 1001) {
            $group = "first";
        }
        if (($this->BlobID >= 5100 && $this->BlobID < 5200) || $this->BlobID == 1002) {
            $group = "second";
        }
        return $descriptionToReturn;
    }

}
