#!/bin/env python
# -*- coding: utf-8 -*-
#
# Usage: runlist.py initial_run_no [final_run_no]
#    initial_run_no, final_run_no:
#       range of run numbers to be listed.
#    -np: does not show proton counts

from __future__ import print_function
from __future__ import absolute_import
import sys
import os
import glob
import Manyo as mm
import Manyo.MLF as mmlf
import Manyo.Utsusemi as mu
import utsusemi.ana.Reduction.BaseCommandsInEla as BC

ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
if ver<2.5:
    from elementtree.ElementTree import ElementTree
else:
    from xml.etree.ElementTree import ElementTree
    
#########################################
def BCMakeRunList( start_run=-1, end_run=-1, output="~/run_list.txt",flag_proton=1,offset_sec=0.0,isCT8n=True,devTemp="LS340",devGonio="Gonio" ):
    """
    Make run list 
    @param start_run (int) start run number to be listed.
    @param end_run (int) start run number to be listed.
    @param output (string) output file name
    @param flag_proton (int) 0: no protons, 1:with protons
    @param offset_sec (float) offset second for Measurement Period to get protons
    @return None
    """
    #data_folder = os.environ["UTSUSEMI_DATA_DIR"]
    #sys_name = os.environ["UTSUSEMI_SYS_NAME"]
    data_folder = mu.UtsusemiEnvGetDataDir()
    sys_name = mu.UtsusemiEnvGetInstCode()
    run_number_wild = "%s%06d_*"%(sys_name,start_run)
    import glob
    print("--- Searching run number like %s"%(run_number_wild))
    run_folder_list = glob.glob( os.path.join( data_folder, sys_name+"*" ) )
    run_folder_list.sort()
    run_folder = ""
    for a_run_folder in run_folder_list:
        run_number_list = glob.glob( os.path.join( a_run_folder, run_number_wild ) )
        if len(run_number_list)!=0:
            run_folder=a_run_folder
            break
    if run_folder=="":
        raise UserWarning( "Run folder not found :",run_folder )
    print("--- fin")
    run_number_list.sort()
    isIROHA2Used = False
    if len(run_number_list)!=0:
        fullpath = os.path.join( run_folder, run_number_list[-1],"params",("run%06d.xml"%(start_run) ) )
        if os.path.exists( fullpath ):
            isIROHA2Used = True
    
    from . import MakeRunListFromParamsIROHA2 as MR
#    if (isIROHA2Used):
#        import ana.Reduction.MakeRunListFromParamsIROHA2 as MR
#    else:
#        import ana.Reduction.MakeRunListFromParams as MR
    
    args = ["dummy"]
    if start_run<=0:
        message = "start_run must be set."
        raise UserWarning(message)
    args.append( "%d" % start_run )
    
    if end_run>0:
        args.append( "%d" % end_run )
    
    if output[:2]=="~/":
        #output = os.path.join( os.getenv("UTSUSEMI_USR_PRIV_HOME") ,output[2:] )
        output = os.path.join( mu.UtsusemiEnvGetWorkDir() ,output[2:] )
    args.append( "-f" )
    args.append( output )
    
    if flag_proton==0:
        args.append( "-np" )
    
    if isIROHA2Used:
        args.append( "-r" )
        args.append( data_folder )
        args.append( "-T" )
        args.append( devTemp )
        args.append( "-G" )
        args.append( devGonio )
        
    args.append( "-os" ) # set offset_sec 
    args.append( offset_sec )
    
    if isCT8n:
        args.append( "-CT8n" )
    
    print(args)
    
    MR.MakeRunList( args )

############################################



#########################################
def usage(argv):
    print("------------------------------------------------------------------------")
    print("Usage  %s [option] initial_run_no [final_run_no]" % (argv[0]))
    print("       initial_run_no, final_run_no : range of run numbers to be listed.")
    print("------------------------------------------------------------------------")
    print("Option")
    print("       -np          : does not show proton counts")
    print("       -f filename  : saves the list as a text file named filename")
    print("       -r directory : top directory of IROHA2 log folders, like /opt/mlfsoft/data.")
    print("------------------------------------------------------------------------")
    sys.exit(0)

#########################################
# copied from GetMeasBC.py by Y. Inamura
def GetMeasBC( runNo, flag_proton, offset_sec=0.0, isCT8Neutron=False ):
    TT = mu.T0TreatToolsNeunet()
    #st_RUNNO="%3s%06d" % (os.environ["UTSUSEMI_SYS_NAME"],runNo)
    st_RUNNO="%3s%06d" % (mu.UtsusemiEnvGetInstCode(),runNo)
    
    #root_data_dir = os.environ["UTSUSEMI_DATA_DIR"]
    #inst_code = os.environ["UTSUSEMI_SYS_NAME"]
    root_data_dir = mu.UtsusemiEnvGetDataDir()
    inst_code = mu.UtsusemiEnvGetInstCode()
    list_DATA_folder = os.listdir( root_data_dir )
    target_dir = ""    
    
    for a_DATA_folder in list_DATA_folder:
        if a_DATA_folder.find(inst_code)<0:
            continue
        
        a_path = os.path.join( root_data_dir, a_DATA_folder )
        if os.path.isdir(a_path):
            list_DATA = os.listdir( a_path )
            for a_data_dir in list_DATA:
                if a_data_dir.find( st_RUNNO )==0:
                    target_dir = os.path.join( a_path, a_data_dir )
                    break
        if target_dir!="":
            break
    
    if target_dir=="":
        err_message = "There is no data;"+st_RUNNO
        raise UserWarning(err_message)
    edb_list = os.listdir( target_dir )
    edb_list.sort()
    target_edb=""
    for a_edb in edb_list:
        if ".edb" in a_edb:
            target_edb = a_edb
            break
    if target_edb=="":
        err_message = "There is no edb data;"+st_RUNNO
        raise UserWarning(err_message)
    TT.readOrgEvent( os.path.join( target_dir, target_edb ) )
    mpv = TT.putMeasPeriodFromT0()
        
    if mpv.size()!=14:
        err_message = "False to get measuring period from Event Data"
        raise UserWarning(err_message)
    start_date = "%04d/%02d/%02d" % (int(mpv[0]),int(mpv[1]),int(mpv[2]))
    start_time = "%02d:%02d:%02d" % (int(mpv[3]),int(mpv[4]),int(mpv[5]))
    end_date   = "%04d/%02d/%02d" % (int(mpv[7]),int(mpv[8]),int(mpv[9]))
    end_time   = "%02d:%02d:%02d" % (int(mpv[10]),int(mpv[11]),int(mpv[12]))
    
    
    if flag_proton == 0:  # does not show proton counts
        proton = "     ---  "
    else:  # show proton counts
#        print "NormByBeamCurrent(runNo=%d)" % runNo
#        print "     begin date and time = ",start_date," ",start_time
#        print "       end date and time = ",end_date," ",end_time
    
        bc = BC.getBeamCurrent(start_date, start_time, end_date, end_time, offset_sec, isCT8Neutron)
        proton = "%10d" % (int(bc))

    return (runNo,start_date,start_time,end_date,end_time,proton)

#########################################
def MakeRunList(argv):
    ET = ElementTree()

    Output = [] # list where the output is stored

    # header of the output
    #Output.append("  run#           start                 end              protons     T_A    T_B     gonio")

    argc = len(argv) # number of argument
    if (argc < 2):
        usage(argv) # show help and exit

    flag_proton = 1
    offset_sec = 0.0
    # analysis arguments
    output_name=""
    data_folder="/opt/mlfsoft/data"
    devname_temp="LS340"
    devname_gonio="Gonio-1"
    init_no = -1
    fin_no = -1
    ind = 1
    isCT8Neutron = False
    while(True):
        if argv[ind]=="-np":
            flag_proton = 0
        elif argv[ind]=="-f":
            if ind==len(argv)-1:
                usage(argv)
            ind += 1
            output_name=argv[ind]
        elif argv[ind]=="-r":
            if ind==len(argv)-1:
                usage(argv)
            ind += 1
            data_folder=argv[ind]
        elif argv[ind]=="-os":
            if ind==len(argv)-1:
                usage(argv)
            ind += 1
            offset_sec=float( argv[ind] )
        elif argv[ind]=="-T":
            if ind==len(argv)-1:
                usage(argv)
            ind += 1
            devname_temp= argv[ind]
        elif argv[ind]=="-G":
            if ind==len(argv)-1:
                usage(argv)
            ind += 1
            devname_gonio= argv[ind]
        elif argv[ind]=="-CT8n": # if use CT8Neutron 
            isCT8Neutron=True
        else:
            if init_no<0:
                init_no = int(argv[ind])
            else:
                fin_no = int(argv[ind])

        ind += 1
        if ind>=len(argv):
            break

    if init_no<0:
        usage(argv)
    if fin_no<0:
        fin_no = init_no

    run_no = init_no # run number
    
    if isCT8Neutron:
        proton_source="CT8n"
    else:
        proton_source="CT9"
        
    #Output.append("  run#           start                 end          protons(%s)     T_A    T_B     gonio"%(proton_source))
    Output.append("  run#           start                 end          protons(%s)     T_A   T_D2   T_D3     gonio  kicker\ncomment"%(proton_source))
    
    #sys_name = os.environ["UTSUSEMI_SYS_NAME"]
    sys_name = mu.UtsusemiEnvGetInstCode()
    while(True):
        # xml file where the experimental condition is stored
        run_number_wild = "%s%06d_*"%(sys_name,run_no)
        run_folder_list = glob.glob( os.path.join( data_folder, sys_name+"*" ) )
        run_folder_list.sort()
        run_folder = ""
        for a_run_folder in run_folder_list:
            run_number_list = glob.glob( os.path.join( a_run_folder, run_number_wild ) )
            if len(run_number_list)!=0:
                run_folder=a_run_folder
                break
        if run_folder=="":
            raise UserWarning( "Run folder not found :",run_folder)
        
        if len(run_number_list)!=0:
            fullpath = os.path.join( run_folder, run_number_list[-1],"params",("run%06d.xml"%(run_no) ) )
            tt=mmlf.BoostXmlParser()
            tt.Load(fullpath)
            #gonio_path="runInfo/paramsList/devParam,name:%s/params/param/th"%(devname_gonio)
            #temp_path="runInfo/paramsList/devParam,name:%s/params/tmpcnt"%(devname_temp)
            runno_path="runInfo/runNo"
            runno = int( tt.PutContent(runno_path) )
            
            gonio_path="runInfo/measRslt/devLog,devName:%s/devStatus/params/param/th"%(devname_gonio)
            temp_path="runInfo/measRslt/devLog,devName:%s/devStatus/params/param"%(devname_temp)
            # read temperature
            temp_cnt = tt.PutContent(temp_path+"/temperature")
            if temp_cnt=="":
                temp = "  --- "
            else:
                temp = "%6.2f" % (float(temp_cnt))
                
            # read temperature A
            temp_a_cnt = tt.PutContent(temp_path+"/temperature_a")
            if temp_a_cnt == "":
                temp_a = "  --- "
            else:
                temp_a = "%6.2f" % (float(temp_a_cnt))

#            # read temperature B
#            temp_b_cnt = tt.PutContent(temp_path+"/temperature_b")
#            if temp_b_cnt == "":
#                temp_b = temp
#            else:
#                temp_b = "%6.2f" % (float(temp_b_cnt))
            
            # read temperature D2
            temp_d2_cnt = tt.PutContent(temp_path+"/temperature_d2")
            if temp_d2_cnt == "":
                temp_d2 = "  --- "
            else:
                temp_d2 = "%6.2f" % (float(temp_d2_cnt))
            
            # read temperature D3
            temp_d3_cnt = tt.PutContent(temp_path+"/temperature_d3")
            if temp_d3_cnt == "":
                temp_d3 = "  --- "
            else:
                temp_d3 = "%6.2f" % (float(temp_d3_cnt))
            
            # read angle of the gonio
            gonio_cnt = tt.PutContent(gonio_path)
            if gonio_cnt == "":
                gonio = "    ---    "
            else:
                gonio = "%8.4f" % (float(gonio_cnt))
            
            #temp_path="runInfo/measRslt/devLog,devName:DAQ/logs/log,compName:group2:Kicker0"
            temp_path="runInfo/measRslt/devLog,devName=DAQ/logs/log,compName=group2:Kicker0/eventNum"
            # read temperature
            kicker_cnt = tt.PutContent(temp_path)
            if kicker_cnt=="":
                kicker = "  --- "
            else:
                kicker = kicker_cnt
            
            temp_path="runInfo/comment"
            # read temperature
            comment_cnt = tt.PutContent(temp_path)
            if comment_cnt=="":
                comment = "  --- "
            else:
                comment = comment_cnt 
            del tt
            """
            # open the xml file
            e = ET.parse(open(fullpath))
            
            # read the run number from xml file to check consistency
            runno = e.find(".//runNo").text
            runno = int(runno)

            # read set temperature
            temp_el = e.find(".//temperature")
            if temp_el == None:
                temp = "  --- "
            else:
                temp = "%6.2f" % (float(temp_el.text))

            # read temperature A
            temp_a_el = e.find(".//temperature_a")
            if temp_a_el == None:
                temp_a = "set_T="
            else:
                temp_a = "%6.2f" % (float(temp_a_el.text))

            # read temperature B
            temp_b_el = e.find(".//temperature_b")
            if temp_b_el == None:
                temp_b = temp
            else:
                temp_b = "%6.2f" % (float(temp_b_el.text))

            # read angle of the gonio
            gonio_el = e.find(".//th")
            if gonio_el == None:
                gonio = "    ---    "
            else:
                gonio = "%8.4f" % (float(gonio_el.text))
            """
            
            # get proton current
            result = GetMeasBC(runno, flag_proton, offset_sec, isCT8Neutron)

            # store the output in the list
            #Output.append("%6d   %s %s   %s %s   %s   %s %s   %s" % (runno, result[1], result[2], result[3], result[4], result[5], temp_a, temp_b, gonio))
            Output.append("%6d   %s %s   %s %s   %s   %s %s %s  %s  %s\n%s" % (runno, result[1], result[2], result[3], result[4], result[5], temp_a, temp_d2, temp_d3, gonio, kicker, comment))

        run_no += 1
        if run_no > fin_no:
            break

    print() # print blank line
    print("----------------------------------------------------------------------------------------")
    for out in Output: # print the output
        print(out)
    print("----------------------------------------------------------------------------------------")
    
    # save as text file
    if output_name!="":
        print("     Output file=",output_name)
        fo = open( output_name, "w" )
        for out in Output:
            fo.write( out+"\n" )
        fo.close()
    
#########################################

if __name__ == '__main__':
    print("Input Start Run No.")
    StartRunNo = raw_input()
    print("Input End Run No.")
    EndRunNo = raw_input()

    fname = "RunListFrom%sTo%s.txt" %(StartRunNo, EndRunNo)

    BCMakeRunList(int(StartRunNo),int(EndRunNo), fname, flag_proton=1, offset_sec=0.0, isCT8n=False, devTemp="LS350Loop1", devGonio="ComCryoRotStage")
