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

'''
$RCSfile: datasource.py,v $
$Revision: 905 $
$Author: markus $
$Date: 2008-04-30 11:57:10 +0200 (Mi, 30. Apr 2008) $
'''

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.configtool.cmfupgrade import cmfUpgrade
from biocase.cmfinfo            import CMFTemplateListClass


############################################################################################################
#
#   MAIN
#
#===========================================================================================================

# check authentication!
if dsaObj is None:
    execfile( os.path.abspath( os.path.join( os.path.dirname( __file__ ), 'main.cgi' ) ))
    sys.exit()

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

# use the datasource.html template to get datasource overview
tmpl = PageMacro('Content', PageMacro.DELMODE)
tmpl.load('Content', os.path.join(templateDir, '_datasource.html'))

# PSF
psfObj = dsaObj.getPSFObj(tmp=False)

# upgrade object
upgradeObj = cmfUpgrade()

#
# ACTIONS
#
if action == 'del':
    # "remove" CMF. rename it to xml.bak and remove older baks if existing
    old = os.path.join(dsaObj.getDsaDir(), form.getfirst('schema',None))
    new = os.path.join(dsaObj.getDsaDir(), "_" + form.getfirst('schema',None) + ".bak")
    log.debug( "Removing CMF %s from datasource" %old)
    if os.path.isfile(new):
        os.unlink(new)
    os.rename(old, new)

elif action == 'upgrade':
    # upgrade an existing cmf
    oldCmf = os.path.join( dsaObj.getDsaDir(), form.getfirst('schema',None) )
    newNS  = form.getfirst('targetns')
    newCmfObj, missingConcepts, upgradeTuple = upgradeObj.getUpgradedCmfObj( oldCmf, newNS)
    if newCmfObj is None:
        log.error( "ERROR ! CMF could not be upgraded. Unknown error" )
    else:
        newCmf = os.path.join( dsaObj.getDsaDir(), upgradeTuple[0] )
        newCmfObj.writeCMF(newCmf)
#
# FILL TEMPLATE
#
# general
tmpl['dsa'] = dsa
tmpl['wrapper_url'] = dsaObj.getBioCASeAccessPoint()

# dbconnection status
tmpl['status'] = dsaObj.getDBConnectionStatus()

# number of aliases in PSF
tmpl['num_ta'] = str(len( psfObj.getTableAliasList() ))

# list of dsa schemas
slObj = dsaObj.getSchemaListObj()
log.debug("DSA CMFList: %s"%str(slObj))

# list of duplicate dsa schemas with the same NS
origSchemas = {}
duplicateList = []
for sObj in slObj:
    if origSchemas.has_key(sObj.NS):
        duplicateList.append( {'schema':sObj.name, 'schemaorig':origSchemas[sObj.NS].name} )
    else:
        origSchemas[sObj.NS] = sObj
tmpl.expand('Content', 'schemaduplicatelist', duplicateList)

# create existing cmf schema list...
DsaSchemaList = []
for sObj in slObj:
    entry = {}
    entry['schema'] = sObj.name
    entry['schema_file'] = os.path.split(sObj.file)[1]
    entry['namespace'] = sObj.NS
    entry['num_mappings'] = str(sObj.mappings)
    entry['num_concepts'] = str(sObj.concepts)
    entry['schemalist.upgrades'] = [ {'ns':ns, 'targetschema':upgrTup[0][:-4]} for ns, upgrTup in upgradeObj.listPossibleUpgradeTuples(sObj.NS).items() if ns not in origSchemas.keys() ]
    if len(entry['schemalist.upgrades']) == 0:
        entry['supress_upgrade_start'] = '<!--'
        entry['supress_upgrade_end'] = '-->'
    else:
        entry['supress_upgrade_start'] = ''
        entry['supress_upgrade_end'] = ''
    DsaSchemaList.append( entry )
tmpl.expand('Content', 'schemalist', DsaSchemaList)


# UPDATE PSF WITH THESE SCHEMAS ?
CmfUpdates = [sObj.getLastUpdated() for sObj in slObj if sObj is not None]
if len(CmfUpdates) > 0:
    lastCMFupdate = max(CmfUpdates)
    psfUpdate = psfObj.getPSFUpdatedWhen()
    if lastCMFupdate > psfUpdate:
        log.debug("Need to update PSF with CMF list. Last PSF update at %s, last CMF update %s" %( str(psfUpdate), str(lastCMFupdate)))
        psfObj.delAllSchemas()
        for sObj in slObj:
            psfObj.addSchema(sObj.NS, sObj.file)
        psfObj.writePSFile()
    else:
        log.debug("No need to update PSF with CMF list. Last PSF update at %s, last CMF update %s" %( str(psfUpdate), str(lastCMFupdate)))
else:
    log.debug("No CMFs found. PSF will not be updated")
    
# list of cmf templates
tmplSlObj = slObj
tmplSlObj = CMFTemplateListClass()
log.debug("Full Template CMFList: %s"%str(tmplSlObj))
# dont show already configured schemas. Identify duplicates by their NS
for sObj in slObj:
    tmplSlObj.removeSchema(NS=sObj.NS)
dropDown = getDropDownOptionHtml( dict([('--select--','--select--')] + [(sObj.name,os.path.split(sObj.file)[1])for sObj in tmplSlObj]), '--select--')
tmpl['newschema_options'] = dropDown


#
# print HTML !
#
printOverHTTP( tmpl )
