from os import path as path
import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing

import FWCore.PythonUtilities.LumiList as LumiList
import FWCore.ParameterSet.Types as CfgTypes

# this ivars thing, whatever this is, will hold the names to the input/output files
ivars = VarParsing.VarParsing('analysis')


#HLT_source = 'HLT' # 'HLT2'
#withHLT = True
'''
input_files, isMC, dtag = ('file:/eos/user/a/asikdar/MC_2016/RunIISummer16MiniAODv3_TT_TuneCUETP8M2T4_13TeV-powheg-pythia8_PUMoriond17_94X_mcRun2.root',), True, 'TT'
input_files, isMC, dtag = ('file:/eos/user/a/asikdar/MC_2016/RunIISummer16MiniAODv3_DYJetsToLL_M-10to50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8_PUMoriond17_94X_mcRun2.root',), True, 'DYJets'
input_files, isMC, dtag = ('file:/eos/user/a/asikdar/MC_2016/RunIISummer16MiniAODv3_WJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8_PUMoriond17_94X_mcRun2.root',), True, 'WJets'

input_files, isMC, dtag = ('file:/eos/user/a/asikdar/MC_2016/RunIISummer16MiniAODv3_QCD_HT2000toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_PUMoriond17_94X_mcRun2.root',), True, 'QCD2016-2000'
input_files, isMC, dtag = ('file:/eos/user/a/asikdar/MC_2016/RunIISummer16MiniAODv3_ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1_PUMoriond17_94X_mcRun2.root',), True, 'ST_tw'

#input_files, isMC, dtag = ('file:/eos/user/a/asikdar/MC_Samples_2017/ST_tW_top_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8.root',), True, 'ST_tw'
input_files, isMC, dtag = ('file:/eos/user/a/asikdar/MC_Samples_2017/TTToHadronic_TuneCP5_13TeV-powheg-pythia8_545BA300-0243-E811-868A-7CD30AD09934.root',), True, 'TTToHardonic'
#input_files, isMC, dtag = ('file:/eos/user/a/asikdar/data_2016/SingleMuon_Run2016B-17Jul2018_ver1-v1_miniAOD.root',), False, 'SingleMuon_Run2016B-17Jul2018_ver1-v1'
#input_files, isMC, dtag = ('file:/eos/user/a/asikdar/data_2016/SingleElectron_Run2016B_17Jul2018_ver1-v1_miniAOD.root',), False, 'SingleElectron_Run2016B-17Jul2018_ver1-v1'


#input_files, isMC, dtag = ('file:/eos/user/a/asikdar/MC_2016/RunIISummer16MiniAODv3_TT_TuneCUETP8M2T4_13TeV-powheg-pythia8_PUMoriond17_94X_mcRun2.root',), True, 'TT'
dataset_reco_name = '2017legacy'
'''
#input_files, isMC, dtag = ('root://cms-xrd-global.cern.ch//store/mc/RunIISummer20UL17MiniAODv2/TTTo2L2Nu_TuneCP5_13TeV-powheg-pythia8/MINIAODSIM/106X_mc2017_realistic_v9-v1/00000/0F43B007-70E3-5D4A-8291-91308D2A46B1.root',), True, 'TTTo2L2Nu'
#input_files, isMC, dtag = ('root://cms-xrd-global.cern.ch//store/mc/RunIISummer20UL17MiniAODv2/TTToHadronic_TuneCP5_13TeV-powheg-pythia8/MINIAODSIM/106X_mc2017_realistic_v9-v2/110000/029813D5-62C1-A84A-8711-5EEA17D5C096.root',), True, 'TTToHadronic'
#input_files, isMC, dtag = ('root://cms-xrd-global.cern.ch//store/mc/RunIISummer20UL17MiniAODv2/TTToSemiLeptonic_TuneCP5_13TeV-powheg-pythia8/MINIAODSIM/106X_mc2017_realistic_v9-v1/00000/005708B7-331C-904E-88B9-189011E6C9DD.root',), True, 'TTToSemileptonic'
#input_files, isMC, dtag = ('root://cms-xrd-global.cern.ch//store/mc/RunIISummer20UL17MiniAODv2/ST_tW_top_5f_inclusiveDecays_TuneCP5_13TeV-powheg-pythia8/MINIAODSIM/106X_mc2017_realistic_v9-v2/100000/022728E1-D23D-5D4A-9B86-36827C4761F5.root',), True, 'STop'
#input_files, isMC, dtag = ('root://cms-xrd-global.cern.ch//store/mc/RunIISummer20UL17MiniAODv2/DYJetsToLL_M-50_TuneCP5_13TeV-madgraphMLM-pythia8/MINIAODSIM/106X_mc2017_realistic_v9-v2/120000/005B6A7C-B0B1-A745-879B-017FE7933B77.root',), True, 'DYJetsToLL'
#input_files, isMC, dtag = ('root://cms-xrd-global.cern.ch//store/mc/RunIISummer20UL17MiniAODv2/WJetsToLNu_TuneCP5_13TeV-madgraphMLM-pythia8/MINIAODSIM/106X_mc2017_realistic_v9-v1/00000/03568087-779D-C44D-B4EB-ACD0B8655049.root',), True, 'WJetsToLNu'

ivars.inputFiles=(
'root://cms-xrd-global.cern.ch//store/mc/RunIISummer20UL17MiniAODv2/TTTo2L2Nu_TuneCP5_13TeV-powheg-pythia8/MINIAODSIM/106X_mc2017_realistic_v9-v1/00000/0F43B007-70E3-5D4A-8291-91308D2A46B1.root' 
)
#isMC = True
#withHLT = True
#HLT_source = 'HLT'
#dataset_reco_name = '2017legacy'  #'2016legacy'
#record_scheme = ['tauID','Dilep']
#dtag = "TTTo2L2Nu"

# MC or Data is used everywhere
isMC = {isMC}   # PARAMETER
dtag = '{dtag}' # PARAMETER
dataset_reco_name = '{dataset_reco_name}' # PARAMETER
record_scheme = {record_scheme} # PARAMETER

#record_scheme = ['tauID','Dilep'] # ('signal','recordAll') # ('signal',) # ('tauID',) # ('tauCands',) #  Dilep MonitorHLT tauIDantiIso jets'



#ivars.inputFiles = input_files
to_tag = True

#output_file = './NtuplerAnalyzer_%s_METfilters%s_UL2017_%s_%s_test13.root' % ('MC' if isMC else 'Data', 'OFF' if to_tag else 'ON', dtag, '_'.join(record_scheme))
ivars.outputFile = dtag + '.root'
# get and parse the command line arguments
ivars.parseArguments()

#print input_files
#print output_file
print ("dtag: %s") % dtag

process = cms.Process("Demo")

############ for Run2 geometry
process.load("Configuration.Geometry.GeometryRecoDB_cff") 
process.load("Configuration.StandardSequences.MagneticField_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
 
#process.GlobalTag.globaltag = cms.string('94X_dataRun2_v10') #for legacy 2016 data
#process.GlobalTag.globaltag = cms.string('94X_mcRun2_asymptotic_v3') # for leagcy 2016 MC
#process.GlobalTag.globaltag = cms.string('106X_dataRun2_v32') #for Ultra legacy 2017 data
#process.GlobalTag.globaltag = cms.string('106X_mc2017_realistic_v8') # for ultra leagcy 2017 MC

# https://twiki.cern.ch/twiki/bin/viewauth/CMS/PdmVAnalysisSummaryTable
if dataset_reco_name == '2017legacy':
    if isMC:
        #process.GlobalTag.globaltag = cms.string('94X_mc2017_realistic_v17')
        process.GlobalTag.globaltag = cms.string('106X_mc2017_realistic_v8') # for ultra leagcy 2017 MC
    else:
        #process.GlobalTag.globaltag = cms.string('94X_dataRun2_v11')
        process.GlobalTag.globaltag = cms.string('106X_dataRun2_v32') #for Ultra legacy 2017 data
else:
    if isMC:
       # process.GlobalTag.globaltag = cms.string('80X_mcRun2_asymptotic_2016_TrancheIV_v6')
       process.GlobalTag.globaltag = cms.string('94X_mcRun2_asymptotic_v3')
    else:
        # so, era H has different global tag
        # process.GlobalTag.globaltag = cms.string('80X_dataRun2_Prompt_v16') if '2016H' in dtag else cms.string('80X_dataRun2_2016SeptRepro_v7')
        process.GlobalTag.globaltag = cms.string('94X_dataRun2_v10')

# some feature for tracks?
process.load("TrackingTools.TransientTrack.TransientTrackBuilder_cfi")
#process.options = cms.untracked.PSet(
#    wantSummary = cms.untracked.bool( True ),
#    #SkipEvent = cms.untracked.vstring('ProductNotFound')
#)

# initialize MessageLogger and output report
process.load("FWCore.MessageLogger.MessageLogger_cfi")

#process.MessageLogger.cerr.threshold = 'INFO'
##process.MessageLogger.categories.append('Demo')
#process.MessageLogger.cerr.INFO = cms.untracked.PSet(
#    #limit = cms.untracked.int32(-1)
#    limit = cms.untracked.int32(10000)
#)

process.options   = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )

#process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 10000

process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )

process.source = cms.Source("PoolSource",
    # replace 'myfile.root' with the source file you want to use
    #fileNames = cms.untracked.vstring(
    #    'file:/afs/cern.ch/cms/Tutorials/TWIKI_DATA/TTJets_8TeV_53X.root'
    #)
    fileNames = cms.untracked.vstring(ivars.inputFiles)
)


######### the b fragmentation systematics calculator
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')

#from doc on particlelevel https://twiki.cern.ch/twiki/bin/viewauth/CMS/ParticleLevelProducer
process.load("GeneratorInterface.RivetInterface.mergedGenParticles_cfi")
process.load("GeneratorInterface.RivetInterface.genParticles2HepMC_cfi")
process.genParticles2HepMC.genParticles = cms.InputTag("mergedGenParticles")
process.load("GeneratorInterface.RivetInterface.particleLevel_cfi") 

# from b-frag example https://gitlab.cern.ch/CMS-TOPPAG/BFragmentationAnalyzer
process.mergedGenParticles = cms.EDProducer("MergedGenParticleProducer",
                    inputPruned = cms.InputTag("prunedGenParticles"),
                        inputPacked = cms.InputTag("packedGenParticles"),
                   )
from GeneratorInterface.RivetInterface.genParticles2HepMC_cfi import genParticles2HepMC
process.genParticles2HepMC = genParticles2HepMC.clone( genParticles = cms.InputTag("mergedGenParticles") )
process.load("GeneratorInterface.RivetInterface.particleLevel_cfi")
process.particleLevel.excludeNeutrinosFromJetClustering = False
process.load('TopQuarkAnalysis.BFragmentationAnalyzer.bfragWgtProducer_cfi')

############### electron scale correction 
#https://twiki.cern.ch/twiki/bin/viewauth/CMS/EgammaMiniAODV2#Applying_the_Energy_Scale_and_sm
#https://twiki.cern.ch/twiki/bin/viewauth/CMS/EgammaUL2016To2018
from RecoEgamma.EgammaTools.EgammaPostRecoTools import setupEgammaPostRecoSeq
setupEgammaPostRecoSeq(process,
                       runEnergyCorrections=True,
                       runVID=True, #saves CPU time by not needlessly re-running VID, if you want the Fall17V2 IDs, set this to True or remove (default is True)
                       era='2017-UL') # a sequence egammaPostRecoSeq has now been created and should be added to your path, eg process.p=cms.Path(process.egammaPostRecoSeq)

#process.load("UserCode.NtuplerAnalyzer.CfiFile_cfi")
process.load('RecoTauTag.Configuration.loadRecoTauTagMVAsFromPrepDB_cfi') #for tau mva 
import UserCode.NtuplerAnalyzer.CfiFile_cfi as std_config

process.ntupler = std_config.ntupler
#process.demo.minTracks=1000

#print process.ntupler['tau_objs_name']
print getattr(process.ntupler, 'tau_objs_name')

parameter_names_per_reco = std_config.parameter_names_per_reco

for param_name, param_defs in parameter_names_per_reco.items():
    param_def = param_defs['default']
    for same_definition_group in param_defs:
        if dataset_reco_name in same_definition_group:
            param_def = param_defs[same_definition_group]

    setattr(process.ntupler, param_name, param_def)

print dataset_reco_name, process.ntupler.tau_objs_name, process.ntupler.tau_VLoose_ID



if dataset_reco_name in ('2016legacy', '2017legacy'):
    updatedTauName = "slimmedTausNewID" #name of pat::Tau collection with new tau-Ids
    import RecoTauTag.RecoTau.tools.runTauIdMVA as tauIdConfig
    tauIdEmbedder = tauIdConfig.TauIDEmbedder(process, cms, debug = False,
                    updatedTauName = updatedTauName,
                    toKeep = ["deepTau2017v2p1", #deepTau TauIDs
                               ])
    tauIdEmbedder.runTauID()

#process.ntupler.dtag = cms.string('MC2016_TT_powheg')
process.ntupler.isMC = cms.bool(isMC)
process.ntupler.is2016legacy = cms.bool(dataset_reco_name == '2016legacy')
process.ntupler.isLocal = cms.bool(False)
process.ntupler.withHLT = cms.bool({withHLT})
#process.ntupler.withHLT = cms.bool(withHLT)
process.ntupler.dtag = cms.string(dtag)
#process.ntupler.HLT_source = cms.string(HLT_source)

# triggers
if '2017legacy' in dataset_reco_name:
    process.ntupler.muHLT_MC1   = cms.string("HLT_IsoMu27_v*"  )
    process.ntupler.muHLT_MC2   = cms.string("HLT_IsoMu27_v*")
    process.ntupler.muHLT_Data1 = cms.string("HLT_IsoMu27_v*"  )
    process.ntupler.muHLT_Data2 = cms.string("HLT_IsoMu27_v*")
    process.ntupler.elHLT_Data  = cms.string("HLT_Ele35_WPTight_Gsf_v*")
    process.ntupler.elHLT_MC    = cms.string("HLT_Ele35_WPTight_Gsf_v*")

# for LumiDump:
process.ntupler.input = cms.untracked.vstring('root://cms-xrd-global.cern.ch//store/mc/RunIISummer20UL17MiniAODv2/TTTo2L2Nu_TuneCP5_13TeV-powheg-pythia8/MINIAODSIM/106X_mc2017_realistic_v9-v1/00000/0F43B007-70E3-5D4A-8291-91308D2A46B1.root')
process.ntupler.outfile = cms.string('/afs/cern.ch/work/a/asikdar/private/CMSSW_10_6_20/src/UserCode/NtuplerAnalyzer/Summer20UL17_TTTo2L2Nu_powheg_crabtemplate_lumidump.root')

theLumiMask = path.expandvars("") # -- lumi should be handled via CRAB3, but for now I leave this config option available in Ntupler for local runs
process.ntupler.lumisToProcess = LumiList.LumiList(filename = theLumiMask).getVLuminosityBlockRange()

print 'record_scheme', record_scheme
if record_scheme:
    process.ntupler.record_tauID         = cms.bool('tauID'         in record_scheme)
    process.ntupler.record_tauCands      = cms.bool('tauCands'      in record_scheme)
    process.ntupler.record_tauIDantiIso  = cms.bool('tauIDantiIso'  in record_scheme)
    process.ntupler.record_bPreselection = cms.bool('bPreselection' in record_scheme)
    process.ntupler.record_MonitorHLT    = cms.bool('MonitorHLT'    in record_scheme)
    process.ntupler.record_ElMu          = cms.bool('ElMu'          in record_scheme)
    process.ntupler.record_Dilep         = cms.bool('Dilep'         in record_scheme)
    process.ntupler.record_jets          = cms.bool('jets'          in record_scheme)
    process.ntupler.record_signal        = cms.bool('signal'        in record_scheme)
    process.ntupler.record_all           = cms.bool('recordAll'     in record_scheme)


### Set output
process.TFileService = cms.Service("TFileService",
	fileName = cms.string(ivars.outputFile)
)


process.load('Configuration.StandardSequences.Services_cff')
process.load("RecoMET.METFilters.metFilters_cff") # back to this

#process.load('RecoMET.METFilters.BadPFMuonFilter_cfi')
#process.load('UserCode.NtuplerAnalyzer.BadPFMuonFilter_cfi') #switched off for now
#process.BadPFMuonFilter.muons = cms.InputTag("slimmedMuons")
#process.BadPFMuonFilter.PFCandidates = cms.InputTag("packedPFCandidates")
#process.BadPFMuonFilter.taggingMode = cms.bool(to_tag)
#process.BadPFMuonFilter.filter = cms.bool(not to_tag)


#"BadChargedCandidateFilter" not recommended https://twiki.cern.ch/twiki/bin/viewauth/CMS/MissingETOptionalFiltersRun2#2018_2017_data_and_MC_UL
#process.load('RecoMET.METFilters.BadChargedCandidateFilter_cfi')
#process.BadChargedCandidateFilter.muons = cms.InputTag("slimmedMuons")
#process.BadChargedCandidateFilter.PFCandidates = cms.InputTag("packedPFCandidates")
#process.BadChargedCandidateFilter.taggingMode = cms.bool(to_tag)
#process.BadChargedCandidateFilter.filter = cms.bool(not to_tag)


if dataset_reco_name in '2017legacy_2016legacy':
    #run_path = process.rerunMvaIsolationSequence * process.NewTauIDsEmbedded * \
        #process.BadPFMuonFilter * process.BadChargedCandidateFilter
    run_path = process.rerunMvaIsolationSequence * process.slimmedTausNewID
        
else:
#    run_path = process.BadPFMuonFilter
    run_path = process.slimmedTausNewID

if isMC:
    print "MC"
    # include bFrag systematics
    run_path = run_path * process.mergedGenParticles*process.genParticles2HepMC*process.particleLevel*process.bfragWgtProducer
    

else:
    print "data"

run_path = run_path * process.ntupler
process.p = cms.Path(run_path)


