<?php

/**
 * Klasa zapisująca i wyświetlająca miniatury obrazów
 *
 * @author wojtek
 */
class Rtn_Image_Core {

	/**
	 *
	 * @param string $method metoda zmiany wielkości (box|resize)
	 * @param string $width szerokość obrazu wyjściowego w pikselach
	 * @param string $height wysokość obrazu wyjściowego w pikselach
	 * @param string $path lokalizacja pliku wraz z nazwą względem $system_path
	 * @param string $systemPath ścieżka systemowa, domyślnie APPLICATION_PATH
	 */
	public static function generate($method, $width, $height, $path, $system_path = APPLICATION_PATH) {
		$local_file = static::getSaveLocation($path, $width, $height);
		try {
			if (file_exists($local_file)) {
				$thumb = PhpThumb_PhpThumbFactory::create($local_file);
				$thumb->show();
			} else {
				$thumb = PhpThumb_PhpThumbFactory::create($system_path . $path);
				static::$method($thumb, $width, $height);
				$thumb->save(static::getSaveLocation($path, $width, $height));
			}

			$thumb->show();
		} catch (Exception $e) {
			$thumb = PhpThumb_PhpThumbFactory::create(PUBLIC_PATH . Core_Module_Module::getInstance()->getFrontImgPath() . 'img_placeholder.png');
			static::$method($thumb, $width, $height);
			$thumb->show();
		}
	}

	public static function getSaveLocation($path, $width, $height) {
		$info = new SplFileInfo($path);
		$dest_path = PUBLIC_PATH . '/images/' . $width . '/' . $height . '/' . $info->getPath();
		if (!is_dir($dest_path)) {
			static::createSavePath($dest_path);
		}

		return $dest_path . '/' . $info->getFilename();
	}

	protected static function createSavePath($dest_path) {
		mkdir($dest_path, 0775, true);
	}

	protected static function box(&$thumb, $width, $height) {
		if ($width > $height) {
			$thumb->resize($width);
		} else {
			$thumb->resize($height);
		}

		$thumb->cropFromCenter($width, $height);
	}

	protected static function resize(&$thumb, $width, $height) {
		$thumb->resize($width);
		$thumb->resize($height);
	}

}

?>
