#!/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
from CondCore.TagCollection import TagTree,CommonUtils,entryComment
class tagTreeDelete:
    def __init__(self):
        """
        Class add entry in the tag inventory
        usage: %prog [options]
        -c, --connect=connectstring: connection string to the tag DB (required)
        -u, --user=user: user name
        -p, --password=password: password
        -P, --path=path: path to authentication.xml
        -T, --tree=treename: tree to delete. Note: the tree name is case insensitive, it is always internally converted to uppercase.
        -a, --all: print all
        -n, --node: root node of the branch to delete
        -v, --verbose: switch on verbose mode
        -h, --help: print usage
        """
        self.__parser=OptionParser()
        self.__connectstring=''
        self.__user=''
        self.__password=''
        self.__authpath='.'
        self.__branch=''
        self.__node=''
        self.__all=True
        self.__treename=''
        self.__verbose=False
    def parsecmdln(self):
        """
        Parse commandline
        """
        usage = "usage: \%prog [options] \n"
        self.__parser.add_option("-c","--connect",action="store",dest="connectstring",type="string",help="connection string to the tag DB(required)")
        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="delete the tree with given name. Note: the tree name is case insensitive, it is internally converted to uppercase")
        self.__parser.add_option("-a","--all",action="store_true",dest="all",help="delete all tag trees")
        self.__parser.add_option("-b","--branch",action="store",dest="branch",help="root node of the branch to delete")
        self.__parser.add_option("-n","--node",action="store",dest="node",help="delete a single node. The rest of the tree will be rearranged")
        self.__parser.add_option("-v","--verbose",action="store_true",dest="verbose",help="verbose mode")
        self.__parser.set_defaults(connectstring='')
        self.__parser.set_defaults(user='')
        self.__parser.set_defaults(password='')
        self.__parser.set_defaults(authpath='.')
        self.__parser.set_defaults(branch='')
        self.__parser.set_defaults(node='')
        self.__parser.set_defaults(all=False)
        self.__parser.set_defaults(verbose=False)
        (options, args) = self.__parser.parse_args()
        if not self.__parser.values.connectstring:
            raise OptionValueError("option -%s is required"%('c'))
        if self.__parser.values.treename and self.__parser.values.all:
            raise OptionValueError("option -%s and -%s are exclusive"%('a','T'))
        if self.__parser.values.branch and self.__parser.values.all:
            raise OptionValueError("option -%s and -%s are exclusive"%('a','b'))
        if self.__parser.values.node and self.__parser.values.all:
            raise OptionValueError("option -%s and -%s are exclusive"%('a','n'))
        if self.__parser.values.node and self.__parser.values.branch:
            raise OptionValueError("option -%s and -%s are exclusive"%('b','n'))
        self.__treename=self.__parser.values.treename
        self.__all=self.__parser.values.all
        self.__branch=self.__parser.values.branch
        self.__node=self.__parser.values.node
        self.__connectstring=self.__parser.values.connectstring
        self.__user=self.__parser.values.user
        self.__password=self.__parser.values.password
        self.__authpath=self.__parser.values.authpath
        self.__all=self.__parser.values.all
        self.__verbose=self.__parser.values.verbose
        if not self.__parser.values.treename and not self.__parser.values.all:
            self.__all=True
        if self.__parser.values.verbose is True:
            print 'connectstring: ',self.__connectstring
            print 'user: ',self.__user
            print 'password: ',self.__password
            print 'authpath: ',self.__authpath
            if self.__all is True:
                print 'delete all: ',self.__all
            else:
                print 'delete tree: ',self.__treename
                if len(self.__branch)==0 and len(self.__node)==0:
                    print 'delete from root'
                if len(self.__branch)!=0:
                    print 'delete branch',self.__branch
                if len(self.__node)!= 0:
                    print 'delete node: ',self.__node
    def deleteme(self):
        """
        delete requested tag tree and selected branch or all
        """
        #context = coral.Context()
        #if self.__verbose is True:
        #    context.setVerbosityLevel( 'DEBUG' )
        #else:
        #    context.setVerbosityLevel( 'ERROR' )
        svc = coral.ConnectionService()
        #try:
        config=svc.configuration()
        os.environ['CORAL_AUTH_PATH']=self.__authpath
        config.setDefaultAuthenticationService('CORAL/Services/XMLAuthenticationService')
        session = svc.connect( self.__connectstring,accessMode = coral.access_Update )
        if self.__all is True:
            transaction=session.transaction()
            transaction.start(True)
            schema=session.nominalSchema()
            tablelist=schema.listTables()
            treelist=[]
            for tablename in tablelist:
                if tablename.find("TAGTREE_TABLE_") != -1:
                    treelist.append(tablename[len("TAGTREE_TABLE_"):])
            transaction.commit()
            for treename in treelist:
                tree=TagTree.tagTree(session,treename)
                tree.deleteSubtree( 'ROOT' )
                entrycomment=entryComment.entryComment(session)
                if entrycomment.existCommentTable() is True:
                  entrycomment.clearAllEntriesForTable(CommonUtils.treeTableName(treename))
            del session
            return
        tree=TagTree.tagTree(session,self.__treename)
        if self.__branch=='' and self.__node=='':
            tree.deleteSubtree( 'ROOT' )
            entrycomment=entryComment.entryComment(session)
                if entrycomment.existCommentTable() is True:
                  entrycomment.clearAllEntriesForTable(CommonUtils.treeTableName(self.__treename))
        else:
            if self.__branch != '':
                print self.__branch
                tree.deleteSubtree(self.__branch)
                entrycomment=entryComment.entryComment(session)
                if entrycomment.existCommentTable() is True:
                  nodes=tree.getSubtree(self.__branch)
                  for node in nodes:  
                    entrycomment.deleteCommentForId(CommonUtils.treeTableName(self.__treename),node.nodeid)
                  
            if self.__node != '':
                tree.deleteNode(self.__node)
                if entrycomment.existCommentTable() is True:
                    node=getNode(self.__node)
                    entrycomment.deleteCommentForId(CommonUtils.treeTableName(self.__treename),node.nodeid)
        del session
        #except Exception, e:
        #    print str(e)
if __name__ == "__main__":
    tagdelete=tagTreeDelete() 
    tagdelete.parsecmdln()
    tagdelete.deleteme()
    

