# This file is part of the Coral project.
# Please read the copyright notice in the LICENSE file.

"""
Keeps a database with different user and runtime options.

Options stored by default in '~/.coral/configuration'

"""

__author__="Ivan Porres iporres@abo.fi"
__date__="13.02.02"


import os
import inspect

from coral.util.user import getUserHome,getUserName

_theCoralConfiguration=None
_language = None





def _createCoralConfiguration():
    global _theCoralConfiguration
    global _language
    import coral
    conf = None
    
    for dirname in ['~/.coral/','~/.coral/coral','~/.coral/coral/addins','~/.coral/coral/lang']:
        try:
            os.mkdir(os.path.expanduser(dirname))
        except:
            pass
    
    for fname in ['~/.coral/coral/__init__.py','~/.coral/coral/addins/__init__.py']:
        try:
            os.stat(os.path.expanduser(fname))
        except:
            fd=open(os.path.expanduser(fname),"w")
            fd.close()
                              
    cfile = os.path.expanduser('~/.coral/configuration')
    coral.Language.__getLanguage__("Config", 0, 1)
    try:
        conf = coral.loadInternalDocument(cfile).contents()[0]
    except:
        if not conf:
            l = coral.Language.__getLanguage__("Config", 0, 1)
            conf = l.getElement("Configuration")()
            conf.name = "UserCoralConfiguration"
            try:
                saveConfig(conf, cfile)
            except RuntimeError:
                pass # happens when we can't save the config

    _language = conf.__type__().__language__()
    _theCoralConfiguration=conf

    c = _language.getElement("Configuration")
    c.__addOperation__(coral.PyOperation(saveConfig, "Python", "", 0))
    c.__addOperation__(coral.PyOperation(addOption, "Python", "", 0))
    c.__addOperation__(coral.PyOperation(dGet, "Python", "", 0))


def saveConfig(config, thefile = None):
    "Saves current configuration in ~/.coral/configuration"
    import coral
    if not thefile:
        thefile = os.path.expanduser('~/.coral/configuration')
    coral.saveModel(thefile, config)

def addOption(conf, list_of_ns, value, weak = 1):
    global _theCoralConfiguration
    global _language
    ns = conf

    option = list_of_ns[-1]
    list_of_ns = list_of_ns[:-1]

    for name in list_of_ns:
        found = 0
        for i in ns.ownedElement:
            if i.name == name:
                ns = i
                found = 1
                break
        if not found:
            e = _language.getElement("Namespace").newAtom()
            e.name = name
            ns.ownedElement.add(e)
            ns = e
    opt = ns.ownedElement.select(lambda x: x.name == option)
    if not opt:
        opt = _language.getElement("Parameter").newAtom()
        opt.name = option
        opt.namespace = ns
    else:
        if weak:
            return
        opt = opt[0]
    opt.value = value

def dGet(configuration, list_of_ns, default=""):
    global _language
    import coral
    
    option = list_of_ns[-1]
    list_of_ns = list_of_ns[:-1]

    if list_of_ns == ["Coral"]:
        if option == "install_path":
            return coral.installation_path
        if option == "version":
            return coral.version
        if option == "user_home":
            home = getUserHome()
            if home: return home
            assert 0, "Couldn't determine home directory!"

    ns = configuration

    for name in list_of_ns:
        found = 0
        for i in ns.ownedElement:
            if i.name == name:
                ns = i
                found = 1
                break
        if not found:
            return default
    opt = ns.ownedElement.select(lambda x: x.name == option)
    if not opt:
        return default
    return str(opt[0].value)

def getCoralConfiguration():
    global _theCoralConfiguration
     
    if not _theCoralConfiguration:
        _createCoralConfiguration()

    assert(_theCoralConfiguration)
    return _theCoralConfiguration


