from Gaudi.Configuration import *
from Configurables import DaVinci, FilterDesktop, CombineParticles, OfflineVertexFitter
from PhysSelPython.Wrappers import AutomaticData, Selection, SelectionSequence, DataOnDemand
from Configurables import FilterDesktop
from Configurables import LoKiSvc



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

from Configurables import DaVinci

# Define a make TOS filter function
def makeTOSFilter(name,specs):
    from Configurables import TisTosParticleTagger
    tosFilter = TisTosParticleTagger(name+'TOSFilter')
    tosFilter.TisTosSpecs = specs
    tosFilter.ProjectTracksToCalo = False
    tosFilter.CaloClustForCharged = False
    tosFilter.CaloClustForNeutral = False
    tosFilter.TOSFrac = {4:0.0, 5:0.0}
    return tosFilter
# Define a tosSelection function
def tosSelection(sel,specs):
    from PhysSelPython.Wrappers import Selection
    '''Filters Selection sel to be TOS.'''
    tosFilter = makeTOSFilter(sel.name(),specs)
    return Selection(sel.name()+'TOS', Algorithm=tosFilter,
                     RequiredSelections=[sel])

# Define a nominal selection for the muon.
def _NominalMuSelection( ):
        return "(TRCHI2DOF < 4. ) &  (P> 3000.*MeV) &  (PT> 1500.*MeV)"\
               "& (TRGHOSTPROB < 0.35)"\
               "& (MIPCHI2DV(PRIMARY)> 16. )"
    
# Define a nominal selection for the proton with no PID.
def _NominalPSelection():
        return "(TRCHI2DOF <  6.) &  (P> 15000.*MeV) &  (PT> 1000.*MeV)"\
               "& (TRGHOSTPROB < 0.35)"\
               "& (MIPCHI2DV(PRIMARY)> 16.)"\
               "& (switch(ISMUON,1,0) < 1)"




    ##### Muon Filter ######
def _muonFilter(name):
        
        from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
        from PhysSelPython.Wrappers import Selection
        from StandardParticles import StdLooseMuons
        _mu = FilterDesktop( Code = _NominalMuSelection()  )

        _muSel=Selection("Mu_for"+ name,
                         Algorithm=_mu,
                         RequiredSelections = [StdLooseMuons])
        _muSel = tosSelection(_muSel,{'L0.*Muon.*Decision%TOS':0})
        
        
        return _muSel


    ###### Proton Filter ######
def _protonFilter(name):
        
        from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
        from PhysSelPython.Wrappers import Selection
        from StandardParticles import StdLooseProtons
        
        _pr = FilterDesktop( Code = _NominalPSelection()  )
        _prSel=Selection("p_for" + name,
                         Algorithm=_pr,
                         RequiredSelections = [StdLooseProtons])
        
        
        return _prSel



def _Definitions():
        return [ 
            "from LoKiPhys.decorators import *",
            "from LoKiTracks.decorators import *",
            "Lb_PT = PT",
	    "Lb_MCORR = BPVCORRM"
                           ]
	
def _Lb2pMuNuVub_Lb(name):
        from GaudiConfUtils.ConfigurableGenerators import CombineParticles
        from PhysSelPython.Wrappers import Selection
        
	_pMu = CombineParticles(DecayDescriptors = ["[Lambda_b0 -> p+ mu-]cc"], ReFitPVs = True
)
        _pMu.Preambulo = _Definitions()
	_pMu.CombinationCut = "(AM> 1000.*MeV)" 
	_pMu.MotherCut = "(VFASPF(VCHI2/VDOF)< 4.) & (BPVDIRA> 0.994)"\
                    "& (Lb_PT > 1500.)"\
                    "& (BPVVDCHI2 > 150.)" 
	_pMu.ReFitPVs = True
            
        _pMuSel=Selection("pMu_high_Lb_for"+name,
                         Algorithm=_pMu,
                         RequiredSelections = [_protonFilter(name),_muonFilter(name)])
         
        _LbSel = tosSelection(_pMuSel,{'Hlt2.*TopoMu2Body.*Decision%TOS':0,'Hlt2.*SingleMuon.*Decision%TOS':0})
        return _LbSel



seq = SelectionSequence("LbpMuNu.SafeStripTrig", 
                          TopSelection = _Lb2pMuNuVub_Lb("Lb2pmunu"))


#
# Configuration of SelDSTWriter
#
enablePacking = True

from DSTWriters.microdstelements import *
from DSTWriters.Configuration import (SelDSTWriter,
                                      stripDSTStreamConf,
                                      stripDSTElements
                                      )

SelDSTWriterElements = {
    'default'               : stripDSTElements(pack=enablePacking)
    }

SelDSTWriterConf = {
    'default'               : stripDSTStreamConf(pack=enablePacking)
    }


dstWriter = SelDSTWriter( "MyDSTWriter",
                          StreamConf = SelDSTWriterConf,
                          MicroDSTElements = SelDSTWriterElements,
                          OutputFileSuffix ='Filtered',
                          SelectionSequences = [seq]
                          )


#
# DaVinci Configuration
#
from Configurables import DaVinci
DaVinci().Simulation = True
DaVinci().EvtMax = -1                        # Number of events
DaVinci().HistogramFile = "DVHistos.root"
DaVinci().appendToMainSequence( [ seq.sequence() ] )
DaVinci().appendToMainSequence( [ dstWriter.sequence() ] )


