<?php

/**
 * Caching plugin
 *
 * @uses Zend_Controller_Plugin_Abstract
 */
class Pampa_Controller_Plugin_Cache extends Zend_Controller_Plugin_Abstract {

  /**
   *  @var bool Whether or not to disable caching
   */
  public static $doNotCache = TRUE;
  /**
   * @var Zend_Cache_Frontend
   */
  public $cache;
  /**
   * @var string Cache key
   */
  public $key;

  /**
   * Constructor: initialize cache
   *
   * @param  array|Zend_Config $options
   * @return void
   * @throws Exception
   */
  public function __construct(Zend_Cache_Core $cache) {

    if (!($cache instanceof Zend_Cache_Core)) {
      throw new Exception("Invalid Zend_Cache instance");
    }

    $this->cache = $cache;
  }

  /**
   * Start caching
   *
   * Determine if we have a cache hit. If so, return the response; else,
   * start caching.
   *
   * @param  Zend_Controller_Request_Abstract $request
   * @return void
   */
  public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {
    if (Pampa_Auth_Cms::getInstance()->hasIdentity() || APPLICATION_ENV == 'development' || !$request->isGet()) {
      self::$doNotCache = TRUE;
      return;
    }

    $path = $request->getPathInfo();

    $this->key = md5($path);
    if (false !== ($response = $this->getCache())) {
      $response->sendResponse();
      exit;
    }
  }

  public function getCache() {
    if (($response = $this->cache->load($this->key)) != false) {
      return $response;
    }
    return false;
  }

  /**
   * Store cache
   *
   * @return void
   */
  public function dispatchLoopShutdown() {
    if (self::$doNotCache || $this->getResponse()->isRedirect() || (null === $this->key)) {
      return;
    }

    $this->cache->save($this->getResponse(), $this->key);
  }

  public static function cache($cache){
    self::$doNotCache = !$cache;
  }
}