# This module contains some global variables used in the Extracto
# module.


import os
_cwd = os.path.split(__file__)[0]


# DATAPATH
# This variable contains the full path to a directory that stores
# various data files needed by these algorithms.  This variable is
# used by the datafile.py module.
DATAPATH = os.path.join(_cwd, "data")

# APPPATH
# This variable contains the full path to a directory that contains
# helper applications.
APPPATH = os.path.join(_cwd, "apps")


# db
# The db variable mediates accesses to database objects.
from Extracto import Database
class db:
    KNOWN_DATABASES = {
        'jchangdb' : 1,
        'medlinedb' : 1,
        'abbreviationdb' : 1
        }
    
    def __init__(self):
        self._dbcache = {}

    def _closedb(self, name):
        if not self.KNOWN_DATABASES.has_key(name):
            raise ValueError, "I can't close %s" % name
        if not self._dbcache.has_key(name):
            return
        del self._dbcache[name]
    
    def _opendb(self, name):
        if self._dbcache.has_key(name):
            return self._dbcache[name]
        if not self.KNOWN_DATABASES.has_key(name):
            raise ValueError, "I can't create %s" % name
        x = Database.MySQLDatabase(
            user='jchang', passwd='myac4me',
            host='acronym', port=1521,
            db=name)
        self._dbcache[name] = x
        return x

    def close(self, dbname=None):
        if dbname is None:
            dbs = self._dbcache.keys()
        else:
            dbs = [dbname]
        for db in dbs:
            self._closedb(db)

    def __getattr__(self, attr):
        if self.KNOWN_DATABASES.has_key(attr):
            return self._opendb(attr)
        raise AttributeError, attr
    
db = db()
