#!/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python
# -*- coding: UTF-8 -*-

'''
$RCSfile: system.py,v $
$Revision: 897 $
$Author: markus $
$Date: 2008-04-29 18:15:52 +0200 (Di, 29. Apr 2008) $
The BioCASE querytool
'''

import os, sys
# ***** include the biocase.lib directory in the python sys path for importing *****
execfile( os.path.abspath( os.path.join( os.path.dirname( __file__ ), os.pardir, os.pardir, 'lib', 'biocase', 'adjustpath.py' ) ))

from biocase.configtool.general import *
from biocase.tools.caching   import clearCache
import biocase.configuration
import biocase.datasources
from biocase.cmfinfo import CMFTemplateListClass
import string, shutil


def replNone(x, replace_string=''):
    if x is None:
        return replace_string
    else:
        return x
        
############################################################################################################
#
#   MAIN
#
#===========================================================================================================

# check authentication!
authorize(form, dsa=None)

#
# PROCESS FORMS
#
if action == 'dsa_create':
    # create a new DSA
    newdsa = form.getfirst('dsa_name_new', None)
    if newdsa is not None:
        biocase.datasources.createDsa(newdsa, form.getfirst('dsa_template_new', None))
elif action == 'dsa_delete':
    # delete a DSA
    dsaDir = os.path.join(cfg.dsaLocator, form.getfirst('del_dsa', None))
    if os.path.isdir(dsaDir):
        shutil.rmtree(dsaDir)
        log.info("Datasource %s deleted."%dsa)
    else:
        log.error("Cant delete datasource %s. Please remove it manually."%dsa)
elif action == 'cfg_update':
    for opt in cfg._listOptions("server"):
        if form.getfirst("server."+opt) is not None:
            cfg.server.__setOption__(opt, form.getfirst("server."+opt))
    cfg.__save__()
elif action == 'clear_cache':
    clearCache()


#
# CREATE OUTPUT VIA TEMPLATE
#

# load html template
tmpl = PageMacro('Content', PageMacro.DELMODE)
tmpl.load('Content', os.path.join(templateDir, '_system.html'))

# server config
for opt in cfg._listOptions("server"):
    tmpl["server."+opt] = str(getattr(cfg.server, str(opt)))

# DATASOURCES
dsaObjList  = biocase.datasources.getDsaList()
dsaTmplList = [{'dsa':dsaObj.name} for dsaObj in dsaObjList]
tmpl.expand('Content', 'datasourcelist', dsaTmplList)
# DSA TEMPLATES
tmpl['dsa_template_options']=getDropDownOptionHtml([t for t in os.listdir(cfg.dsaTemplateLocator) if not t.startswith('.')],'empty')

# CMF TEMPLATES
cmfTmplListObj = CMFTemplateListClass()
cmfTmplList = [{'name':cmf.name, 'ns':cmf.NS, 'concept_num':str(cmf.concepts)} for cmf in cmfTmplListObj]
tmpl.expand('Content', 'cmftemplates', cmfTmplList)

# ALL CFGs
tmpl['cfgprintout'] = unicode(cfg)


#
# print HTML !
#
printOverHTTP( tmpl )
