<?php

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

use Vn\Lib;
use Vn\Lib\UserException;

/**
 * Uploads a file creating its corresponding sizes.
 */
class Upload extends Vn\Web\JsonRequest
{
	const PARAMS = [
		'name',
		'schema'
	];

	function run ($db)
	{
		$util = new Util ($this->app);

		$schema = $_REQUEST['schema'];
		$name = $_REQUEST['name'];

		// Checks schema

		$info = $util->loadInfo ($schema);
		
		if (!$info)
			throw new UserException (s('Schema not exists'));

		// Checks file name

		if (preg_match ('/[^a-z0-9_]/', $_REQUEST['name']) !== 0)
			throw new UserException (s('Bad file name'));

		// Checks for file errors
		
		if (empty ($_FILES['image']['name']))
			throw new UserException (s('File not choosed'));

		if ($_FILES['image']['error'] != 0)
		{
			switch ($_FILES['image']['error'])
			{
		        case UPLOAD_ERR_INI_SIZE:
		            $message = 'ErrIniSize';
		            break;
		        case UPLOAD_ERR_FORM_SIZE:
		            $message = 'ErrFormSize';
		            break;
		        case UPLOAD_ERR_PARTIAL:
		            $message = 'ErrPartial';
		            break;
		        case UPLOAD_ERR_NO_FILE:
		            $message = 'ErrNoFile';
		            break;
		        case UPLOAD_ERR_NO_TMP_DIR:
		            $message = 'ErrNoTmpDir';
		            break;
		        case UPLOAD_ERR_CANT_WRITE:
		            $message = 'ErrCantWrite';
		            break;
		        case UPLOAD_ERR_EXTENSION:
		            $message = 'ErrExtension';
		            break;
		        default:
		            $message = 'ErrDefault';
		            break;
		    }

			throw new Lib\Exception (s($message));
		}
		
		$maxSize = $db->getValue ('SELECT maxSize FROM imageConfig');

		if ($_FILES['image']['size'] > $maxSize * 1048576)
			throw new UserException (sprintf (s('File size error'), $maxSize));

		// Resizes and saves the image

		$tmpName = $_FILES['image']['tmp_name'];
		$fileName = "{$name}.png";
		$schemaPath = "{$util->dataDir}/$schema";
		$fullFile = "$schemaPath/full/$fileName";
		$symbolicSrc = "../full/$fileName";
	
		$image = Image::create ($tmpName);
		Image::resizeSave ($image, $fullFile, $info['maxHeight'], $info['maxWidth']);

		foreach ($info['sizes'] as $size => $i)
		{
			$dstFile = "$schemaPath/$size/$fileName";
			Image::resizeSave ($image, $dstFile, $i['height'], $i['width'], $i['crop'], $symbolicSrc);
		}

		imagedestroy ($image);
		unlink ($tmpName);
		return TRUE;
	}
}

