#!/usr/bin/env python3
from __future__ import print_function
import ROOT
import RootUtils.HistFile
import sys
import os

if len(sys.argv)<2:
    print("Please specify a ROOT file followed optionally the name of histograms to display (default is to display all)")
    sys.exit(0)

if not os.path.exists(sys.argv[1]):
   print("ERROR File not found: %s"%sys.argv[1])
   sys.exit(1)

targets=sys.argv[2:]

tfile=ROOT.TFile(sys.argv[1])
found=False
if not tfile or not tfile.IsOpen():
    print("ERROR Problems opening file: %s"%sys.argv[1])
    sys.exit(1)

content={}
for key in tfile.GetListOfKeys():
    o=key.ReadObj()
    if isinstance(o,ROOT.TNamed):
        content[o.GetName()]=o

if not targets:
    targets=list(content.keys())
    targets.sort()
    if not targets:
        print("ERROR File does not have any objects to display")
        sys.exit(1)

found=False
it=0
while it<len(targets):
    t=targets[it]
    if not t in content:
        print('ERROR Requested object "%s" not found in file'%t)
        sys.exit(1)
    o=content[t]
    if not 'Draw' in dir(o):
        print('ERROR Object %s does not have a Draw() method and can not be displayed')
        sys.exit(1)
    print("Displaying %s %s"%(o.ClassName(),o.GetName()))
    c=RootUtils.HistFile.create_canvas()
    o.Draw()
    c.Update()
    res=RootUtils.HistFile.pause(back_button=(it>0))
    if res=='back':
        it-=1
    else:
        it+=1
