#!/usr/bin/env python
import os,coral
from optparse import OptionParser, Option, OptionValueError
from CondCore.TagCollection import tagInventory,TagTree,CommonUtils
    
class globaltagSchemaCreator:
    def __init__(self):
        """
        Class add entry in the tag inventory
        usage: %prog [options]
        -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
        -C, --create: create tables. 
        -D, --drop: drop tables related to tree with given name.
        -T, --Tree=treename:  
        -v, --verbose: switch on verbose mode
        -h, --help: print usage
        """
        self.__parser=OptionParser()
        self.__connectstring=''
        self.__user=''
        self.__password=''
        self.__authpath=''
        self.__verbose=False
        self.__mode=0 # 1 is to create; -1 is to drop
        self.__treename=''

    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.")
        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("-C","--create",action="store_true",dest="create",help="create tables. With -T option, it creates tables related to the given tree and inventory tables are created if not existant; with no -T option, only inventory tables are created ")
        self.__parser.add_option("-D","--drop",action="store_true",dest="drop",help="drop tables. With -T option, tables related to the given tree are droped; with no -T option, all tables are droped.")
        self.__parser.add_option("-T","--tree",action="store",dest="treename",help="treename")
        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(create=False)
        self.__parser.set_defaults(drop=False)
        self.__parser.set_defaults(treename='')
        self.__parser.set_defaults(verbose=False)
        (options, args) = self.__parser.parse_args()
        if not options.connectstring:
            raise OptionValueError("option -%s is required"%('c'))
        self.__connectstring=self.__parser.values.connectstring
        
        if not options.drop and not options.create:
            raise OptionValueError("option -%s or -%s is required"%('C','D'))
        if options.drop and options.create:
            raise OptionValueError("option -%s and -%s are exclusive"%('C','D'))
        if options.drop:
            self.__mode=-1
        if options.create:
            self.__mode=1
        if options.treename:
            self.__treename=self.__parser.values.treename
                
        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
        
        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.__mode==-1:
                if len(self.__treename)!=0:
                    print 'Drop tables related to '+self.__treename
                else:
                    print 'Drop all tables'
            else:
                if len(self.__treename)!=0:
                    print 'Create tables related to '+self.__treename
                else:
                    print 'Create tag inventory tables'

    def act(self):
        """Do action
        """
        svc = coral.ConnectionService()
        session=svc.connect(self.__connectstring,accessMode=coral.access_Update)
        if self.__mode==1: #create
            inv=tagInventory.tagInventory(session)
            if inv.existInventoryTable() is False:
               inv.createInventoryTable()
            if len(self.__treename)!=0:
               tt=TagTree.tagTree(session,self.__treename)
               if tt.existTagTreeTable() is False:
                 tt.createTagTreeTable()
               else:
                 print 'tree '+treename+' already exists. Do nothing'
            return
        if self.__mode==-1: #drop
            if len(self.__treename) != 0:
              tt=TagTree.tagTree(session,self.__treename)
              tt.deleteSubtree('ROOT')
            else:
              #delete inventory and all trees
              inv=tagInventory.tagInventory(session)
              inv.dropme()
              CommonUtils.dropAllTreeTables(session)
        del session
if __name__ == "__main__":
    schemamanager=globaltagSchemaCreator() 
    schemamanager.parsecmdln()
    schemamanager.act()
