"""Write MicroDSTs with events from some stripped DST locations.
"""
__author__ = 'Juan Palacios juan.palacios@cern.ch, Roel Aaij roel.aaij@cern.ch'

from Gaudi.Configuration import *
from GaudiConf.Configuration import *
from Configurables import DaVinci

from PhysSelPython.Wrappers import AutomaticData, SelectionSequence, MultiSelectionSequence


## Input Stripping Selections
channels = [ 'Bu2JpsiK', 'Bd2JpsiKstar', 'Bs2JpsiPhi', 'Bd2JpsiKs' ]
selections = [ 'Prescaled', 'Detached', 'Unbiased' ]
lines = { 'Lambdab2JpsiLambda' : [ 'Lambdab2JpsiLambda%sLine' % sel for sel in [ 'DD', 'LL', 'Unbiased' ] ] }
for channel in channels:
    lines[ channel ] = [ '%s%sLine' % ( channel, selection ) for selection in selections ]

def selectionSequences( lines, trunk = '/Event/Dimuon/Phys' ):
    """
    Create a list of MultiSelectionSequences wrapping a list of TES locations.
    """
    selectionSequences = []
    for ( name, sequences ) in lines.items():
        seq = None
        if len( sequences ) == 1:
            seq = SelectionSequence( name, TopSelection = AutomaticData (Location = trunk + '/' + sequences[ 0 ] ) )
        else:
            seqs = [ SelectionSequence( seq, TopSelection = AutomaticData (Location = trunk + '/' + seq ) ) for seq in sequences  ]
            seq = MultiSelectionSequence( name, Sequences = seqs )
        selectionSequences.append( seq )
    return selectionSequences

#uDST writer
from DSTWriters.__dev__.Configuration import MicroDSTWriter, microDSTStreamConf
from DSTWriters.__dev__.microdstelements import *

BetaSConf = microDSTStreamConf()

streamConf = { 'default' : BetaSConf }

BetaSElements = [ CloneRecHeader(),
                  CloneODIN(),
                  ClonePVs(),
                  CloneParticleTrees( copyProtoParticles = True ),
                  ClonePVRelations( "Particle2VertexRelations", True ),
                  CloneBTaggingInfo(),
                  ReFitAndClonePVs(),
                  CloneLHCbIDs(),
                  CloneRawBanks( banks = ['HltSelReports', 'HltDecReports',
                                          'L0DU', 'L0Calo', 'L0CaloError',
                                          'L0Muon', 'L0MuonProcCand', 'L0MuonError' ] ) ]

elementsConf = { 'default' : BetaSElements }

dstWriter = MicroDSTWriter( 'MicroDST',
                            StreamConf = streamConf,
                            MicroDSTElements = elementsConf,
                            OutputFileSuffix = 'BetaS',
                            SelectionSequences = selectionSequences( lines ) )

MessageSvc().Format = "% F%40W%S%7W%R%T %0W%M"

# DaVinci settings
DaVinci().UserAlgorithms = [ dstWriter.sequence() ]
DaVinci().DataType  = "2010"
DaVinci().EvtMax    = -1
DaVinci().PrintFreq = 100
DaVinci().Lumi      = True
DaVinci().InputType = "DST"

# Make sure we only have 1 file open at a time
from Configurables import Gaudi__IODataManager as IODataManager
IODataManager().AgeLimit = 2
