import os

fill = 4643
#fill = '4638a'
#fill = '4638b'
piklefile = 'Nov2015-IT.pkl'
jobs = {'tt': 9, 'it': 14}
#jobs = {'tt': 6, 'it': 10}
#jobs = {'tt': 7, 'it': 11}

DISK = os.path.expandvars("$DISK")

tt_path = DISK + '/data/ST/Aging_Tuples/TT/TTaU/%s/' % fill
it_path = DISK + '/data/ST/Aging_Tuples/IT/T3X2/%s/' % fill
tt_target = DISK + '/data/ST/Aging_Tuples/TT/TTaU/%s.root' % fill
it_target = DISK + '/data/ST/Aging_Tuples/IT/T3X2/%s.root' % fill


# run 'SetupLHCbDirac' and 'lhcb-proxy-init' beforehand!
def download():
    import pickle
    #outs = pickle.load(open('/afs/cern.ch/user/e/egraveri/cmtuser/VetraDev_v15r0/STAging/options/ganga/%s' % piklefile, 'rb'))
    outs = pickle.load(open('/afs/cern.ch/user/e/egraveri/cmtuser/Vetra_v16r0/Tr/TrackMonitors/options/ganga/%s' % piklefile, 'rb'))
    tt_lfns = outs['lfns'][jobs['tt']]
    it_lfns = outs['lfns'][jobs['it']]
    import os
    os.system('mkdir -p %s' % tt_path)
    os.system('mkdir -p %s' % it_path)
    for tt in tt_lfns:
        os.system('dirac-dms-get-file %s' % tt)
        tt_fileid = tt.split('/')[-2]
        os.system('mv Tuple.root %s%s.root' % (tt_path, tt_fileid))
    for it in it_lfns:
        try:
            os.system('dirac-dms-get-file %s' % it)
            it_fileid = it.split('/')[-2]
            os.system('mv Tuple.root %s%s.root' % (it_path, it_fileid))
        except:
            print "Problems with file ", it


# Exit and run "SetupVetra v16r0" before!
def hadd():
    import os
    tt_files = os.listdir(tt_path)
    tt_paths = [tt_path + f for f in tt_files]
    print 'hadd %s %s' % (tt_target, ' '.join(tt_paths))
    os.system('hadd -f %s %s' % (tt_target, ' '.join(tt_paths)))
    it_files = os.listdir(it_path)
    it_paths = [it_path + f for f in it_files]
    #os.system('SetupProject.sh Vetra v16r0')
    print 'hadd -f %s %s' % (it_target, ' '.join(it_paths))
    os.system('hadd -f %s %s' % (it_target, ' '.join(it_paths)))
