<?php



class UcImageCacheManager
{
  protected static $instance;

  protected $cache;

  protected function __construct() {
    $this->loadBaseConfiguration();
  }
  /**
   * Load the base configuration
   */
  public function loadBaseConfiguration() {
    $this->cache = new UcImageCache(array('cache_dir' => sfConfig::get('sf_app_cache_dir').'/uc_image'));
  }

  public static function createImageIdFor($imageUrl) {
    return md5($imageUrl);
  }

  public static function getInstance() {
    if(is_null(self::$instance)) {
      self::$instance = new UcImageCacheManager();
    }

    return self::$instance;
  }

  /**
   * return cached image id
   *
   * @param string $urlImage
   * @param int $mw
   * @param int $mh
   * @return string
   */
  public function getOrCreatedCachedImageId($imageUrl, $mw, $mh, $useTransparency=false, $keepRatio=true) {
    $imageId = self::createImageIdFor($imageUrl);
    $imageKey = $imageId.'-'.$mw.'x'.$mh;

    //not already cached
    if(!$this->cache->has($imageKey)) {
      //$thumbnail = new sfThumbnail($mw, $mh, $keepRatio, true, 80, 'sfImageMagickAdapter');
	  $thumbnail = new sfThumbnail($mw, $mh, $keepRatio, true, 80, 'sfGDAdapter');

      try {
        $thumbnail->loadFile($imageUrl);
      } catch (Exception $e) {
        // Image could not be loaded. Use a default one
        sfContext::getInstance() -> getLogger() -> warning( "Unable to create cached image of ".$imageUrl." for the following reason : ".
          $e->getMessage() .". 404 image will be used");

        if ($mw > $mh) {
          $imagePath = sfConfig::get('app_image_cache_landscape_image_path');
        } else {
          $imagePath = sfConfig::get('app_image_cache_portrait_image_path');
        }

        $thumbnail->loadFile($imagePath);
      }

      $contentType = ($useTransparency) ? null : 'image/jpeg';
      $this->cache->set($imageKey, $thumbnail->toString($contentType));

      // Free all ressources
      $thumbnail->freeSource();
      $thumbnail->freeAll();
    }

    return $imageId;
  }

  public function getImage($imageKey) {
    return $this->cache->get($imageKey);
  }

  public function getImageMd5($imageKey) {
    return $this->cache->getImageMd5($imageKey);
  }
}
