from MetadataService.common import DateTime # FIX times/dates everywhere
from MetadataService.Database import Database

import ZODB
from ZODB import DB
# from ZODB.FileStorage import FileStorage
# from BDBStorage.BDBMinimalStorage import BDBMinimalStorage
# from BDBStorage.BerkeleyBase import BerkeleyConfig
from DirectoryStorage import DirectoryStorage
from MetadataService.InfospaceList import InfospaceList
import os

# FIXME implement referential integrity
class ZODBDatabase(Database,DB):

	def __init__(self,path):
		self.__storage = DirectoryStorage(path)
# 		config = BerkeleyConfig()
# 		config.cachesize = 128*1024
# 		self.__storage = BDBMinimalStorage("MetadataServiceStorage",path,config=config)
		DB.__init__(self,self.__storage)
	
	def open_connection(self):
		return self.open()
		
	def root(self,connection):
		return connection.root()
		
	def close_connection(self,connection):
		connection.close()

	def update_schema(self):
		conn= self.open()
		root = conn.root()
		if not root.has_key("infospaces"):
			self.begin_transaction(conn)
			root["infospaces"] = InfospaceList()
			self.commit_transaction(conn)
		conn.close()
		
	def begin_transaction(self,connection):
		a = get_transaction()

	def abort_transaction(self,connection):
		get_transaction().abort()

	def commit_transaction(self,connection):
		get_transaction().commit()

	def close(self):
		DB.close(self)
		
	def pack(self):
		DB.pack(self)


# data model used here
# 
# map key to object (frozen,serialized object) to be able to unserialize it later
# "/home/music/A-Ha/Take on me.mp3", "lsajfls adjflkasdjfa sfjklasjf oiwejflfj pickled data"
# 
# map key,property,value
# 
# "/home/music","artist","something"
# 
# several columns, all may be NULL, depending on data type:
# value_text  (TEXT)
# value_datetime   (DATETIME)
# value_int    (INTEGER)
# value_float    (DOUBLE)
# 
# the query processor should be smart enough to transform everything into the proper column and operator
# 
# { "property": "artist" , "value" : "*amagador*" , "operator" : "glob" }
#     should be transformed into
# (name = "artist" and value_text like "%amagador%")
# 
# 
# 
# 
# 
