<?php

require_once (__DIR__.'/image-method.php');

use Vn\Hedera\Image;

/**
 * Resizes all images allocated in a directory.
 *
 * @param string $srcDir The source directory
 * @param string $dstDir The destination directory
 * @param integer $maxHeight The maximum height of resized image in pixels
 * @param integer $maxWidth The maximum width of resized image in pixels
 * @param boolean $rewrite Wether to rewrite the destination file if it exits
 **/
class ImageResize extends ImageMethod
{
	function run ()
	{
		$params = [
			 'src_dir'
			,'dst_dir'
			,'max_height'
			,'max_Width'
			,'rewrite'
			,'crop'
			,'symbolic'
		];

		$options = getopt ('', $params);

		if (!$this->checkParams ($options, $params)
			$this->usage ();

		$srcDir = $options['src_dir'];
		$dstDir = $options['dst_dir'];
		$maxHeight = $options['max_height'];
		$maxWidth = $options['max_Width'];
		$rewrite = isset ($options['rewrite']);
		$crop = isset ($options['crop']);
		$symbolic = isset ($options['symbolic']);

		set_time_limit (0);

		$count = 0;
		$dir = opendir ($srcDir);

		if ($dir)
		while ($fileName = readdir ($dir))
		if (!in_array ($fileName, ['.', '..']))
		{
			$srcFile = "$srcDir/$fileName";
			$dstFile = "$dstDir/". substr ($fileName, 0, -4).'.png';
			
			if (!file_exists ($dstFile) || $rewrite)
			try
			{
				$symbolicSrc = ($symbolic) ? $srcFile : NULL;
			
				$image = Image::create ($srcFile);
				Image::resizeSave ($image, $dstFile, $maxHeight, $maxWidth, $crop, $symbolicSrc);
				imagedestroy ($image);
				$count++;
			}
			catch (\Exception $e) {}
		}
		
		return $count;
	}
}

?>