<?php

namespace app\models;

class Photo extends \lithium\data\Model {

	//Tells lithium to store it in mongo as a file (gridFS)
	protected $_meta = array('source' => 'fs.files');
	public $validates = array();


	/** 
     * Generate a cached version under webroot
     * @param string $id The image id as in mongodb
     * @param array $options Possible values are
     *   width
     *   height
     * @return mixed
     */
    public static function version($id, $options = array()) {
        if (!$id)
            return false;
        // This is the same as Photo::first($id) when called from inside itself
        $self = static::first($id);
        return ($self) ? $self->generateVersion($options) : false;
    }

    /**
     * Generate a cached version under webroot
     * @param Document $self The document from the db
     * @param array $options Possible values are
     * @return mixed
     */
    public function generateVersion($self, $options = array()) {
        // This is quite naive, it would fail at .jpeg for example. Be more elaborate on production code!
        $type = substr($self->file->file['filename'], -3);
        $path = LITHIUM_APP_PATH . "/webroot/image/{$self->_id}";
        $originalPath = $path . "." . $type;

        // Always create the original variant if it doesnt exist yet. It is needed for resize
        if (!file_exists($originalPath))
            file_put_contents($originalPath, $self->file->getBytes());
        
        if (isset($options['width']) && isset($options['height'])) {
            $width = (int) $options['width'];
            $height = (int) $options['height'];
            
            $path .= "_{$width}x{$height}.{$type}";
    
            // This requires imagemagick and access to system calls. 
            // It is possible to use gd but it is a much worse alternative so please dont.
            $convertCommand = "convert $originalPath -resize {$width}x{$height}\> $path";
            shell_exec($convertCommand);
            // Return data of the resized version
            return file_get_contents($path);
        }
        // If no width/height were set, just return data of the original
        return $self->file->getBytes();
    }
}

?>