from __future__ import print_function
import utsusemi.ana.Reduction.EventDataToEcm as EDT
import Cmm
import Manyo.MLF as mm
import Manyo.Utsusemi as mu

import os
import glob
import time
import datetime

def GetDiffPattern(run,st,et,wfile,dfile):
    #wfile = "/home/dnaadmin/dev/Diffraction/FB/WiringInfoTYMM20140120.new.xml"
    #dfile = "/home/dnaadmin/dev/Diffraction/FB/DetectorInfoTYMM20140120.xml"
    #run = CombineEventData(run,3)
    CheckT0(run,2)
    CheckT0(run,3)

    #ecm = EDT.GetHistogram( "PSD",run, wfile, dfile,st,et)
    ecm = EDT.GetHistogram( "PSD",run, wfile, dfile,st,et) ## changed by YI at 20140805
    #Cmm.NormByBeamCurrent( dat,1e7)

    return ecm

def GetAverageIQ(ecm):
    av = mm.AverageElementContainerMatrix(ecm)
    ec = av.GetAverage()

    return ec

def CheckT0(runNo,moduleNo):
    #if os.environ.has_key("UTSUSEMI_SYS_NAME"):
    #    ss = os.environ["UTSUSEMI_SYS_NAME"]
    instCode = mu.UtsusemiEnvGetInstCode()
    if instCode!="":
        ss = instCode
        ss = ss + "%06d" %runNo
        moduleNo = "_%02d_" %moduleNo

        #Get EventData Info
        #EventDataPath = os.path.join(os.environ["UTSUSEMI_DATA_DIR"],os.environ["UTSUSEMI_SYS_NAME"],ss+"*")
        EventDataPath = os.path.join(mu.UtsusemiEnvGetInstDataDir(),ss+"*")
        EventDataList = glob.glob(os.path.join(EventDataPath,ss+"*"+moduleNo+"016_*.edb"))
        EventDataList.sort()
        if len(EventDataList) != 0:
            EventDataModifiedTime = os.path.getmtime(EventDataList[-1])
            print("EventDataModifiedTime = ", EventDataModifiedTime)
            print("EventDataPath =", EventDataPath)
            print("EventDataList =", EventDataList[-1])
        else:
            print("Check RunNo. There is no event data files")
            return -1
        #Get T0file Info
        #T0Path = os.environ["HOME"]+"/ana/tmp/"
        T0Path = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","tmp")
        T0Files = ss+"*"+moduleNo+"*.t0b"
        T0filelist = glob.glob(T0Path+T0Files)
        T0filelist.sort()
        if len(T0filelist) != 0:
            T0ModifiedTime = os.path.getmtime(T0filelist[-1])
            print("T0ModifiedTime = ", T0ModifiedTime)
            
            if T0ModifiedTime < EventDataModifiedTime:
                com = "rm "+ T0Path+T0Files
                print("com =", com)
                try:
                    os.system(com)
                except:
                    print("rm Error")
                    return -1
            else:
                print("t0b files are already generated.")
    else:
       print("Check Envitoment variable: MLF_SYS_NAME")
       return -1

def CombineEventData(runNo,moduleNo):
    #if os.environ.has_key("UTSUSEMI_SYS_NAME"):
    #    ss = os.environ["UTSUSEMI_SYS_NAME"]
    instCode = mu.UtsusemiEnvGetInstCode()
    if instCode!="":
        ss = instCode
        ss = ss + "%06d" %runNo
        moduleNo = "_%02d_" %moduleNo

        #Get EventData Info
        #EventDataPath = os.path.join(os.environ["UTSUSEMI_DATA_DIR"],os.environ["UTSUSEMI_SYS_NAME"],ss+"*")
        EventDataPath = os.path.join(mu.UtsusemiEnvGetInstDataDir(),ss+"*")
        NewrunNo = runNo
        WorkList = []
        unitList = []
        if moduleNo == "_00":
            unitList = range(1,8)
        elif moduleNo == "_01_":
            unitList = range(8,15)
        elif moduleNo == "_02_":
            unitList.append(254)
        else:
            unitList = range(15,27)

        for ii in unitList:
            unitNo = "%03d_" %ii
            tempList = glob.glob(os.path.join(EventDataPath,ss+"*"+moduleNo+unitNo+"*.edb"))
            tempList.sort()
            if len(tempList) != 0:
                WorkList.append(unitNo)
                print("unitNo=", unitNo)
                #print "tempList=", tempList
                if len(tempList) >= 1 and NewrunNo == runNo:
                    NewrunNo = runNo+990000
                    if NewrunNo >= 1000000:
                        print("Check the source because NewRunNo is", NewrunNo)
                        return -1
                    MeasDate = glob.glob(EventDataPath)[0].split("_")[-1]
                    print("NewRunNo is:", NewrunNo)
                    print("Measured Data is :", MeasDate)
        
        if runNo != NewrunNo:
            #make New EventData Folder as 99xxxx_YYYYMMDD
            #NewEventDataPath = os.path.join(os.environ["UTSUSEMI_DATA_DIR"],os.environ["UTSUSEMI_SYS_NAME"],os.environ["UTSUSEMI_SYS_NAME"]+str(NewrunNo)+"_"+MeasDate)
            NewEventDataPath = os.path.join(mu.UtsusemiEnvGetInstDataDir(),instCode+"%06d"%(NewrunNo)+"_"+MeasDate)
            
            if os.path.exists(NewEventDataPath):
                print("Data Folder is already made as: ", NewEventDataPath)
            else:
                com = "mkdir "+NewEventDataPath 
                try:
                    print(com)
                    os.system(com)
                except:
                    print("mkdir NewEventDataPath Error")
                    return -1

            #Combine EventDataFiles
            for ii in range(len(WorkList)):
                #EventDataPath = os.path.join(os.environ["UTSUSEMI_DATA_DIR"],os.environ["UTSUSEMI_SYS_NAME"],ss+"_"+MeasDate)
                EventDataPath = os.path.join(mu.UtsusemiEnvGetInstDataDir(),ss+"_"+MeasDate)
                print("Update EventDataPath :", EventDataPath)
                OrgEdbList = glob.glob(os.path.join(EventDataPath,ss+moduleNo+WorkList[ii]+"*.edb"))
                OrgEdbList.sort()
                #print "OrgEdbList",OrgEdbList
                mtimeCheck = 0
                #Check Modified time 
                if os.path.exists(NewEventDataPath):
                    #NewEdbList = glob.glob(os.path.join(NewEventDataPath,os.environ["UTSUSEMI_SYS_NAME"]+str(NewrunNo)+moduleNo+WorkList[ii]+"000.edb"))
                    NewEdbList = glob.glob(os.path.join(NewEventDataPath,instCode+str(NewrunNo)+moduleNo+WorkList[ii]+"000.edb"))
                    #print NewEdbList
                    if len(NewEdbList) != 0:
                        #Check modified Time
                        NewEdbmtime = os.path.getmtime(NewEdbList[-1])
                        OrgEdbmtime = os.path.getmtime(OrgEdbList[-1])
                        if NewEdbmtime < OrgEdbmtime:
                            for jj in range(len(NewEdbList)):
                                com = "rm "+NewEdbList[jj]
                                try:
                                    print("The combined data is older than the edbfile")
                                    print(com)
                                    os.system(com)
                                except:
                                    print("New edb file remove error", com)
                                    return -1
                            print("m", mtimeCheck)
                        else:
                            mtimeCheck = 1
                            print("edb files are already combined as:", NewEdbList[-1])
                #Combine Data main
                if mtimeCheck == 0:
                    for jj in range(len(OrgEdbList)):
                        #com = "cat "+OrgEdbList[jj]+" >> " +os.path.join(NewEventDataPath,os.environ["UTSUSEMI_SYS_NAME"]+str(NewrunNo)+moduleNo+WorkList[ii]+"000.edb")
                        com = "cat "+OrgEdbList[jj]+" >> " +os.path.join(NewEventDataPath,instCode+str(NewrunNo)+moduleNo+WorkList[ii]+"000.edb")
                        print(com)
                        try:
                            os.system(com)
                        except:
                            print("Combine edb files Error",com)
                            return -1
        return NewrunNo
    else:
        print("Check MLF_SYS_NAME")
        return -1
                    
#cat /data/DNA/DNA001000_20130413/DNA001000_02_255_000.edb >> /data/DNA/DNA991000_20130416/DNA991000_02_255_000.edb
 

            
            
     

"""
#           T0Path = "/data/tmp/"+ss+"_0*[01]*.t0b" T.Yamada comment out[121123]
           if(len(T0flist)>=14):
                T0file = T0flist[len(T0flist)-1]
                EventData = "/data/DNA/"+ss+"_*/"+ss +"_01_014_*.edb"
                EDlist = glob.glob(EventData)
                EDlist.sort()
                EDfile = EDlist[-1]
                print "T0file", T0file
                print "EDfile", EDfile
                T0ctime = os.path.getmtime(T0file)
                EDmtime = os.path.getmtime(EDfile)
                if (T0ctime < EDmtime):
                    print com
                    try:
                        os.system(com)
                    except:
                        print "rm Error"
                else:
                    print "TY1"
           else:
                print com
                try:
                    os.system(com)
                except:
                    print "rm Error"
"""     
