<?php

	final class SjCacheFactory
	{
		private static $engines = array();

		public static function registerEngine($id, $classname, $file, $checker, $has_options, $pretty)
		{
			static $path = false;
			if (false === $path) {
				$path = dirname(__FILE__);
			}

			if (function_exists($checker)) {
				if (@include_once($path . '/class.' . $file . '.php')) {
					if (class_exists($classname)) {
						self::$engines[$id] = array($classname, $file, $has_options, $pretty);
						return true;
					}
				}
			}

			return false;
		}

		public static function get(array $options)
		{
			if (empty($options['engine'])) {
				return null;
			}

			$enabled = (isset($options['enabled'])) ? $options['enabled'] : true;
			$persist = (isset($options['persist'])) ? $options['persist'] : false;
			$maxttl  = (isset($options['maxttl']))  ? $options['maxttl']  : 3600;

			$engine = strtolower($options['engine']);

			if (!isset(self::$engines[$engine])) {
				$item = reset(self::$engines);
				$name = key(self::$engines);
				trigger_error('Caching engine "' . $engine . '" is not available, falling back to ' . $name . '.', E_USER_WARNING);
			}
			else {
				$item = self::$engines[$engine];
			}

			$class  = $item[0];
			$params = isset($options['options'][$engine]) ? $options['options'][$engine] : array();

			return call_user_func(array($class, 'instance'), $params, $enabled, $persist, $maxttl);
		}

		public static function getEngines()
		{
			return self::$engines;
		}
	}

?>