# Bryan Schumaker (10/23/2010)
import libsaria

path   = libsaria.path
expand = path.expand
mkdir  = path.mkdir
exists = path.exists
join   = path.join
ls     = path.ls
rm     = path.rm
sep    = path.sep

CACHE_DIR = join(path.saria_dir(), "cache")
mkdir(CACHE_DIR)

class CacheObject:
	def __init__(self, path):
		self.path = path

	def get(self, key, func, *args):
		key = key.replace(sep, "_")
		path = join(self.path, key)
		if not exists(path):
			f = open(path, 'w')
			success = func(f, *args)
			try:
				f.close()
			except:
				pass
			if success:
				return path
			else:
				if exists(path):
					rm(path)

		else:
			return path

	def delete(self, key):
		path = join(self.path, key)
		if exists(path):
			rm(path)

class Cache:
	def keys(self):
		return ls(CACHE_DIR)

	def __getitem__(self, key):
		key = key.replace(sep, "_")
		p = join(CACHE_DIR, key)
		mkdir(p)
		return CacheObject(p)
