#!/usr/bin/env python
import os,coral
from ConfigParser import ConfigParser
from optparse import OptionParser, Option, OptionValueError
from CondCore.TagCollection import CommonUtils,connectstrParser,cacheconfigParser

def update_frontier_connection(conn_str):
    '''updates frontier connection with proxy server information'''
    parser=connectstrParser.connectstrParser(conn_str)
    parser.parse()
    if parser.needsitelocalinfo():
        sitelocalconfig = os.environ.get('$CMS_PATH', '/afs/cern.ch/cms/' ) + "SITECONF/CERN/JobConfig/site-local-config.xml"
        frontierparser=cacheconfigParser.cacheconfigParser()
        frontierparser.parse(sitelocalconfig)
        #print "full frontier string: " + str(parser.fullfrontierStr(parser.schemaname(),frontierparser.parameterdict()))
        return str(parser.fullfrontierStr(parser.schemaname(),frontierparser.parameterdict())) #str because default unicode
    return str(conn_str)

class tagInTrees:
    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, --tag: tag to print on detail(optional)
        -v, --verbose: switch on verbose mode
        -h, --help: print usage
        """
        self.__parser=OptionParser()
        self.__connectstring=''
        self.__user=''
        self.__password=''
        self.__authpath='.'
        self.__tag=''
        self.__pfn=''
        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","--tag",action="store",dest="tag",type="string",help="tag to print")
        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(tag='')
        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'))
        self.__connectstring=update_frontier_connection(self.__parser.values.connectstring)
        self.__user=self.__parser.values.user
        self.__password=self.__parser.values.password
        self.__authpath=self.__parser.values.authpath
        self.__tag=self.__parser.values.tag
        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
            print 'tag: ',self.__tag
    def printme(self):
        """
        print requested tag inventory entry or all
        """
        #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_ReadOnly )
        try:
            intrees=CommonUtils.tagInTrees(session,self.__tag)
            del session
            for (iP,iT) in intrees.items():
                print "\t%s\t%s"%('# Tag #',self.__tag)
                print "\t%s\t%s"%('# pfn #',iP)
                print '\t# Trees #', iT
                print '\n'
        except Exception, e:
            print str(e)
            del session
        
if __name__ == "__main__":
    tagprinter=tagInTrees() 
    tagprinter.parsecmdln()
    tagprinter.printme()
    

