# -*- coding: utf-8 -*-
# @Author: Elena Graverini
# @Date:   2017-04-28 15:34:06
# @Last Modified by:   Elena Graverini
# @Last Modified time: 2017-04-28 16:11:46
from __future__ import print_function
import sys
import os
import ROOT as r


def draw_cali_step(i, sig, noi, layer, sector, ns, fill):
    cuts_noi = "(odinStep==%s && sector==%s)" % (i, sector)
    cuts_sig = "(TrChi2/TrNDoF<3.0) &&"\
               "(GhostP<0.01+0.1/1.6*TrChi2/TrNDoF) &&"\
               "(GhostP<0.01-0.1/3.4*(TrChi2/TrNDoF-5.0))"
    if 'IT' in layer:
        cuts_sig = "(GhostP<0.1*TrChi2/TrNDoF) &&"\
                   "(GhostP<0.2-0.1*(TrChi2/TrNDoF-5.0))"
    cuts_sig = cuts_noi + '&&' + cuts_sig
    c = r.TCanvas()
    h_sig = r.TH1F("h_sig", "Signal histo", 208, -32.0, 176.0)
    h_sig.SetLineWidth(3)
    h_sig.SetLineColor(r.kBlue)
    h_bkg = r.TH1F("h_bkg", "Background histo", 208, -32.0, 176.0)
    h_bkg.SetLineWidth(3)
    h_bkg.SetLineColor(r.kRed)
    noi.Draw("val%s>>h_bkg" % ns, cuts_noi)
    sig.Draw("val%s>>h_sig" % ns, cuts_sig, "same")
    c.Modified()
    c.Update()
    os.system("mkdir -p plot_noise_and_signal")
    c.SaveAs("plot_noise_and_signal/%s_fill%s_%s_val%s_step%s.pdf" % (layer, fill, sector, ns, i))
    h_sig.Delete()
    h_bkg.Delete()


if __name__ == '__main__':

    detector, layer = "TT", "TTaU"

    location = os.path.expandvars('$DISK/data/ST/Aging_Tuples/')
    macros = os.path.expandvars('$CCEHOME/macros/CCEScan/')
    r.gROOT.SetBatch(True)

    fill = int(sys.argv[1])
    sector = int(sys.argv[2])
    ns = int(sys.argv[3])

    filename = location + '/' + detector + '/' + layer + '/%s.root' % fill
    file = r.TFile(filename, 'read')
    sig = file.Get('STADCTrackMonitor/HitInfo/%s' % layer)
    noi = file.Get('STADCTrackMonitor/NoiseInfo/%s' % layer)

    for i in range(66):
        draw_cali_step(i, sig, noi, layer, sector, ns, fill)

    file.Close()
