<?php

/**
 * Core
 *
 * @author Arkadiusz Rychlik <a.rychlik at eppe.com.pl>
 */
class Rtn_ImageWc_Core {
	
	public static function generate($path, $width, $height, $method = 'box', $refresh=false) {
		$imgHash = md5_file($path);
		$cachePath = static::setupDirectory(PUBLIC_PATH.'/images/cache/'.$width.'x'.$height.'/');
		$cachePath .= $imgHash;
		
		try {
			if (file_exists($cachePath) && !$refresh) {
				$thumb = PhpThumb_PhpThumbFactory::create($cachePath);
				$thumb->show();
			} else {
				$thumb = PhpThumb_PhpThumbFactory::create($path);
				static::$method($thumb, $width, $height);
				$thumb->save($cachePath);
			}

			$thumb->show();
		} catch (Exception $e) {
			static::generate(PUBLIC_PATH . Core_Module_Module::getInstance()->getFrontImgPath() . 'img_placeholder.png', $width, $height);
		}
	}
	
	protected static function setupDirectory($path) {
		if( !file_exists($path) ) {
			mkdir($path, 0775, true);
		}
		return $path;
	}
	
	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);
	}
	
}
