<?php
class Stash extends Object {
	static private $cache = array();


# ~ Read from the stash	 - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	static public function read($path, $force = false) {
		$keys = array_filter(explode('.', $path));
		$primary = array_shift($keys);

		# If empty
		if($primary === null || $primary === '') {
			return null;
		}

		$data = null;
		# If not yet cached or reload forced
		if(!isset(self::$cache[$primary]) || $force) {
			$method = "get{$primary}";
			if(method_exists(__CLASS__, $method)) {
				$data = self::$method();
				self::write($primary, $data);
			}

		# Return from cache
		} else {
			$data = self::$cache[$primary];
		}

		return fromPath($data, $keys);
	}


# ~ Write to stash - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public static function write($path, $value = null) {
		return self::$cache[$path] = $value;
	}


# ~ Remove from stash- - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function delete($path) {
		if(isset(self::$cache[$path])) {
			unset(self::$cache[$path]);
		}
		return true;
	}


# ~ Stash categories - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	static public function getCategories() {

		# Get list of all categories
		$categories = array();
		$threadedList = ClassRegistry::init('Category')->find('threaded', array(
			'Stash categories',
			'recursive' => -1
		));

		# Group them bu model
		foreach($threadedList as $i => $category) {
			$categories[$category['Category']['model']][] = $category;
		}

		return $categories;
	}


# ~ Stash modules  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	static public function getModules($inList = false, $includeModuleFields = false) {
		$contain = array('Page');

		if($includeModuleFields) {
			$contain['ModuleFields'] = array('ModuleFieldRules');
		}

		# Get list of all modules
		$modules = ClassRegistry::init('Module')->find('all', array(
			'Stash modules',
			'contain' => $contain,
			'order' => 'Module.ordering ASC'
		));

		# //!! WTF bug ??
		if(!is_numeric(key($modules))) {
			return array();
		}

		if($inList) {
			$list = array();
			foreach($modules as $module) {
				$list[] = $module['Module']['name'];
			}
			$modules = $list;
		}

		return $modules;
	}


# ~ Get modules with validation rules- - - - - - - - - - - - - - - - - - - - - #
	static public function getModulesValidation() {
		$modules = self::getModules(false, true);

		# Store in cache, cause data structure fits to Stash::read('modules')
		self::write('modules', $modules);
		return $modules;
	}

}
