<?php

require_once(__DIR__.'/util.php');

/**
 * Creates a thumb from an existing full image.
 *
 * @param string $schema The name of schema
 * @param string $file The file name
 * @param integer $width The width of the thumb
 * @param integer $height The height of the thumb
 */
class Thumb extends Vn\Web\RestRequest {
	function run() {
		// XXX: Uncomment only to test the script
		//$_SERVER['REQUEST_URI'] = 'catalog/200x200/e_cinerea.png';

		$db = $this->getSysConn();
	
		// Gets parameters from URI.

		$uriSplit = explode('/', $_SERVER['REQUEST_URI']);
		$uriSplit = array_slice($uriSplit, count($uriSplit) - 3, 3);

		if (count($uriSplit) < 3)
			throw new Exception('Bad request');

		$schema = $uriSplit[0];
		$orgFile = $uriSplit[2];
		$file = $orgFile;
	
		if (strrpos($file, '.') === FALSE)
			$file .= '.png';

		$size = explode('x', $uriSplit[1]);

		if (count($size) < 2)
			throw new Exception('Bad request');

		$width =(int) $size[0];
		$height =(int) $size[1];

		// Verifies that it is an allowed size.

		$params = [
			 'schema' => $schema
			,'width' => $width
			,'height' => $height
		];

		$row = $db->getValue(
			'SELECT crop 
				FROM imageCollection s 
				JOIN imageCollectionSize z ON z.collectionFk = s.id 
					WHERE s.name = #schema 
					AND z.width = #width 
					AND z.height = #height'
			,$params
		);

		if (!isset($row))
			throw new Exception('Size not allowed');

		// Creates the thumb.
		
		$util = new Util($this->app);
		$baseDir = "{$util->dataDir}/$schema";
		$srcFile = "$baseDir/full/$file";
		$dstFile = "$baseDir/{$width}x{$height}/$file";
		$symbolicSrc = "../full/$file";

		if (!file_exists($srcFile))
			throw new Exception('Source not exists');
		if (file_exists($dstFile))
			throw new Exception('Destination already exists');

		$image = Image::create($srcFile);
		Image::resizeSave($image, $dstFile, $height, $width, $row, $symbolicSrc);
		imagedestroy($image);
		
		// Sends the thumb to the client
		
		$useXsendfile = $db->getValue('SELECT useXsendfile FROM imageConfig');

		if ($useXsendfile) {
			header("X-Sendfile: $dstFile");
			header("Content-Type: image/png");
		} else
			header("Location: {$_SERVER['REQUEST_URI']}");
	}
}