
##########################################################################
#                                                                        #
#  copyright:          (c) 2003 by Konrad Wojas <wojas@vvtp.tudelft.nl>  #
#                                                                        #
#  This program is free software; you can redistribute it and/or modify  #
#  it under the terms of the GNU General Public License as published by  #
#  the Free Software Foundation; either version 2 of the License, or     #
#  (at your option) any later version.                                   #
#                                                                        #
##########################################################################

import cPickle
import os.path

CACHE_VERSION = 3

class IMDbCache:

	def __init__(self,cachefile=None):
		self.cachefile = cachefile
		# print "cache init"
		if cachefile and os.path.exists(cachefile):
			f = open(cachefile,'r')
			self.cache = cPickle.load(f)
			f.close()
			# print self.cache
			if self.cache.get("VERSION",0) != CACHE_VERSION:
				print "IMDb: Version of cachefile '%s' " % cachefile,
				print "differs from '%s', replacing.." % CACHE_VERSION
				self._newCache()
		else:
			self._newCache()
		
	def _newCache(self):
		# print "New cache"
		self.cache = {
			"queries" : {},
			"details" : {},
			"VERSION" : CACHE_VERSION
		}

	def getDetails(self,url):
		r = self.cache["details"].get(url,None)
		# if r: print "Cache hit details"
		return r

	def addDetails(self,url,details):
		self.cache["details"][url] = details

	def getQuery(self,query):
		r = self.cache["queries"].get(query,None)
		# if r: print "Cache hit query"
		return r

	def addQuery(self,query,results):
		self.cache["queries"][query] = results

	def save(self):
		if self.cachefile:
			# print "cache: saving.."
			f = open(self.cachefile,'w')
			cPickle.dump(self.cache,f)
			f.close()

	def __del__(self):
		self.save()
	
