#!/usr/bin/env python
import os
from ConfigParser import ConfigParser
#from copy import copy
from optparse import OptionParser, Option, OptionValueError
import coral
from CondCore.TagCollection import Node,TagTree,tagInventory
def stripws(myinput):
    result=('').join(myinput.split(' '))
    result=('').join(result.split('\n')) 
    return result
class tagTreeRootBuilder:
    def __init__(self):
        """
        Class add node in the tag tree
        usage: %prog [options]
        -f, --file=filename: configuration file. The connect parameter will be overwritten by option -c.
        -c, --connect=connectstring: connection string to the tag DB. If -c, -f both given -c value will overwrite the connect parameter in the config file.
        -u, --user=user: user name
        -p, --password=password: password
        -P, --path=path: path to authentication.xml
        -T, --tree=treename: name of the tree to create(required). Note: the tree name is case insensitive, it is always internally converted to uppercase.
        -r, --rootname=rootnodename(default 'All')
        -a, --all: attach all tags in the inventory as leafs under the root
        -v, --verbose: switch on verbose mode
        -h, --help: print usage
        """
        self.__parser=OptionParser()
        self.__connectstring=''
        self.__user=''
        self.__password=''
        self.__authpath='.'
        self.__rootname=''
        self.__treename=''
        self.__all=False
        self.__verbose=False        
    def parsecmdln(self):
        """
        Parse commandline
        """
        usage = "usage: \%prog [options] \n"
        self.__parser.add_option("-f","--file",action="store",dest="filename",help="configuration file. The connect parameter will be overwritten by option -c.")
        self.__parser.add_option("-c","--connect",action="store",dest="connectstring",type="string",help="connection string to the tag DB. If -c, -f both given -c value will overwrite the connect parameter in the config file.")
        self.__parser.add_option("-u","--user",action="store",dest="user",type="string",help="user name")
        self.__parser.add_option("-p","--password",action="store",dest="password",type="string",help="password")
        self.__parser.add_option("-P","--path",action="store",dest="authpath",type="string",help="path to authentication.xml")
        self.__parser.add_option("-T","--tree",action="store",dest="treename",type="string",help="name of the tree to create(required). Note: the tree name is case insensitive, it is internally converted to uppercase")
        self.__parser.add_option("-r","--rootname",action="store",dest="rootname",type="string",help="root node name (default \'All\')")
        self.__parser.add_option("-a","--all",action="store_true",dest="all",help="attach all tags in the inventory as leafs under the root(optional). Note: the leafnode names in this case are identical to the tag name")
        self.__parser.add_option("-v","--verbose",action="store_true",dest="verbose",help="verbose mode")
        self.__parser.set_defaults(filename='')
        self.__parser.set_defaults(connectstring='')
        self.__parser.set_defaults(user='')
        self.__parser.set_defaults(password='')
        self.__parser.set_defaults(authpath='.')
        self.__parser.set_defaults(rootname='All')
        self.__parser.set_defaults(all=False)
        self.__parser.set_defaults(verbose=False)
        (options, args) = self.__parser.parse_args()

        if not self.__parser.values.treename:
            raise OptionValueError("option -%s --%s is required "%('T','tree'))
        self.__treename=self.__parser.values.treename
        if options.filename and options.connectstring:
            #raise OptionValueError("option -%s and -%s are exclusive"%('f','c'))
            print 'Warning: -c option ',options.connectstring, 'overwrites the connection string in ',options.filename
        if len(self.__parser.values.authpath)!=0:
            self.__authpath=self.__parser.values.authpath
        else:
            self.__user=self.__parser.values.user
            self.__password=self.__parser.values.password
        self.__verbose=self.__parser.values.verbose
        self.__all=self.__parser.values.all        
        if self.__parser.values.filename!='':
            configparser=ConfigParser()
            configparser.read(self.__parser.values.filename)
            if options.connectstring:
                self.__connectstring=self.__parser.values.connectstring
            else:
                self.__connectstring=configparser.get("COMMON","connect")
            sections=configparser.sections()
            for section in sections:
                treesection=' '.join(['TAGTREE',str.upper(self.__treename)])
                self.__rootname=stripws(configparser.get(treesection,'root'))
            if self.__parser.values.verbose is True:
                print 'config file: ',self.__parser.values.filename
        else:    
            self.__connectstring=self.__parser.values.connectstring
            self.__rootname=self.__parser.values.rootname
        if self.__parser.values.verbose is True:
            print 'connect: ',self.__connectstring
            print 'tree: ',self.__treename
            print 'root: ',self.__rootname

    def createRootNode(self):
        """
        Create root node for the the given tree 
        """
        #context = coral.Context()
        #if self.__verbose is True:
        #    context.setVerbosityLevel( 'DEBUG' )
        #else:
        #    context.setVerbosityLevel( 'ERROR' )
        
        svc = coral.ConnectionService()
        config=svc.configuration()
        os.environ['CORAL_AUTH_PATH']=self.__authpath
        config.setDefaultAuthenticationService('CORAL/Services/XMLAuthenticationService')
        session = svc.connect( self.__connectstring,accessMode = coral.access_Update )
        try:
            mytree=TagTree.tagTree(session,self.__treename)
            if mytree.existTagTreeTable() is False:
                mytree.createTagTreeTable()
            mynode=Node.Node()
            mynode.nodelabel=self.__rootname
            mynode.globalsince=0
            mynode.globaltill=4294967295
            mynode.tagid=0
            mytree.insertNode(mynode,'ROOT')
            if self.__all is True:
                inv=tagInventory.tagInventory(session)
                result=inv.getAllEntries()
                for tag in result:
                    myleaf=Node.Node()
                    myleaf.nodelabel=tag.tagname
                    myleaf.tagid=tag.tagid
                    mytree.insertNode(myleaf,self.__rootname)
        except Exception, e:
            print str(e)
            del session
if __name__ == "__main__":
    tagtreerootbuilder=tagTreeRootBuilder() 
    tagtreerootbuilder.parsecmdln()
    tagtreerootbuilder.createRootNode()
    

