from __future__ import print_function
import Manyo as mm
import Manyo.Utsusemi as mu
import Manyo.DNA as md
import os

from utsusemi.DNA.ana.Reduction.DefaultInstParams import *   #[inamura 120807]
import utsusemi.DNA.ana.Reduction.SearchPathDNA as SPD

__version__ = "0.6"

def GetHistogram(eventtype="PSD",runnumber=10,
                 WiringInfo_xml="WiringInfo.xml",
                 DetectorInfo_xml="DetectorInfo.xml",
                 CaseInfo_xml="",
                 ChopCondInfo_xml="",
                 TOFOffsetFile="",
                 useTrignet=0,
                 starttime=-1.0, endtime=-1.0,
                 isPH=False,
                 isHistogram=True):
    """
    Load EventData and convert to histogram on NEUNET system
    If you use this script, you must set some environment variables at least as below:
       UTSUSEMI_SYS_NAME   : "AMR" for BL14, "SIK" for BL01
       UTSUSEMI_DATA_DIR   : normaly use "/data"
       UTSUSEMI_USR_DIR    : normaly use "/opt/mlfsoft/python-utsusemi"
       Obsoleted environment variables : 
                             USE_E2H_MULTH
          
    @param eventtype (string) 'PSD' or 'N2MON'
    @param runnumber  (int) Run Number
    @param WiringInfo_xml (string) Detector Info xml file
    @param DetectorInfo_xml (string) Detector position setting file
    @param starttime (double) gives range of time to slice evnetdata
    @param endtime (double) gives range of time to slice evnetdata
    @param isPH (bool) make this true if pulse height is required
    @retval DAT        ElementContainerMatrix
    """
    if eventtype=="PSD" or eventtype=="N2MON" or eventtype=="uPSD" or eventtype=="SMPMON" or eventtype=="VANMON":
        #[add 140210 AS]--
        #if os.environ["UTSUSEMI_SYS_NAME"]=="DNA":
        instCode = mu.UtsusemiEnvGetInstCode()
        if instCode=="DNA":
            if useTrignet==4 or useTrignet==5 or useTrignet==6:
                if eventtype=="uPSD":
                    evt = md.UtsusemiEventDataConverterDNAWithHSC()
                    #[add 150218 AS]--
                    if TOFOffsetFile!="":
                        if os.path.exists(TOFOffsetFile):
                            pass
                        else:
                            #TOFOffsetFile=os.path.join(os.sep,"home","dnaadmin","ana","EOrg",TOFOffsetFile)
                            #TOFOffsetFile=os.path.join(os.sep,os.environ["UTSUSEMI_USR_PRIV_HOME"],"ana","EOrg",TOFOffsetFile)
                            ret= SPD.CheckForInput("EOrg",TOFOffsetFile)
                            if ret!="":
                                TOFOffsetFile = ret
                            else:
                                raise UserWarning("EventDataToEcm::GetHistogram >> TOFOffsetFile is not found. (%s)"%(TOFOffsetFile))
                        if os.path.exists(TOFOffsetFile):
                            print("load", TOFOffsetFile, "as TOFOffsetFile")
                            evt.SetTOFOffsetFile(TOFOffsetFile)
                    #--[add 150218 AS]

                elif eventtype=="PSD":
                    evt = mu.UtsusemiEventDataConverterNeunet()
                else:
                    evt = md.UtsusemiEventDataConverterDNAWithHSC()

            else:
                if eventtype=="uPSD":
                    evt = md.UtsusemiEventDataConverterDNA()
                    #[add 150218 AS]--
                    if TOFOffsetFile!="":
                        if os.path.exists(TOFOffsetFile):
                            pass
                        else:
                            #TOFOffsetFile=os.path.join(os.sep,"home","dnaadmin","ana","EOrg",TOFOffsetFile)
                            #TOFOffsetFile=os.path.join(os.sep,os.environ["UTSUSEMI_USR_PRIV_HOME"],"ana","EOrg",TOFOffsetFile)
                            TOFOffsetFile = SPD.CheckForInput("EOrg",TOFOffsetFile)
                        if os.path.exists(TOFOffsetFile):
                            print("load", TOFOffsetFile, "as TOFOffsetFile")
                            evt.SetTOFOffsetFile(TOFOffsetFile)
                    #--[add 150218 AS]
                elif eventtype=="PSD":
                    evt = mu.UtsusemiEventDataConverterNeunet()
                else:
                    evt = md.UtsusemiEventDataConverterDNA()
                    #evt = mu.UtsusemiEventDataConverterNeunet()
        else:
            evt = mu.UtsusemiEventDataConverterNeunet()
        #[add 140210 AS] original
        #evt = mu.UtsusemiEventDataConverterNeunet()
        #[add 140210 AS]--
    else:
        raise UserWarning("EvnetType argument is invalid.")

    
    CommentHead = "EventDataToEcm::GetHistogram >>> "
    print("--------------------------------------------------------------------")
    print("Load EventData using Manyo.Utsusemi.UtsusemiEventDataConverterNeunet")
    print("-------")
    
    #spectcode=os.environ["UTSUSEMI_SYS_NAME"]
    #datapath=os.environ["UTSUSEMI_DATA_DIR"]
    #t0datapath = os.path.join(os.environ["HOME"],"ana","tmp")
    spectcode=mu.UtsusemiEnvGetInstCode()
    datapath=mu.UtsusemiEnvGetDataDir()
    t0datapath = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","tmp")
    
    st_runno="%06d" % runnumber
    #if "UTSUSEMI_USR_PRIV_HOME" in os.environ:
    udir = mu.UtsusemiEnvGetUserDir()
    if udir!="":
        WIpath=os.path.join(udir,"ana","xml",WiringInfo_xml)
    else:
        #WIpath=os.path.join(os.environ["HOME"],"ana","xml",WiringInfo_xml)
        WIpath=os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","xml",WiringInfo_xml)
    #print CommentHead,"wiring file path=",WIpath
    if not os.path.exists( WIpath ):
        #WIpath=os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",WiringInfo_xml)
        WIpath=os.path.join(mu.UtsusemiEnvGetBaseDir(),spectcode,"ana","xml",WiringInfo_xml)
        if not os.path.exists(WIpath):
            msg = CommentHead+"There is no wiring file.",WIpath
            print(msg)
            raise UserWarning(msg)
            
    #DCpath=os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",DetectorInfo_xml)
    #CCpath=os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",ChopCondInfo_xml)

    #20151202 start
    #DCpath=os.path.join(os.environ["HOME"],"ana","xml",DetectorInfo_xml)
    #CCpath=os.path.join(os.environ["HOME"],"ana","xml",ChopCondInfo_xml)
    DCpath=os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","xml",DetectorInfo_xml)
    CCpath=os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","xml",ChopCondInfo_xml)
    #20151202 end

    #CIpath=os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",CaseInfo_xml)
    CIpath=os.path.join(mu.UtsusemiEnvGetBaseDir(),spectcode,"ana","xml",CaseInfo_xml)

    print(CommentHead+"WiringInfo path           =",WIpath)
    print(CommentHead+"DetectorInfo path         =",DCpath)
    print(CommentHead+"CaseInfo path             =",CIpath)
    print(CommentHead+"ChopperConditionInfo path =",CCpath)

    if useTrignet==4 or useTrignet==5 or useTrignet==6:
        ## not use trignet use fast chopper -start

        evt.LoadParamFiles( WIpath, DCpath )
        evt.LoadChopCondFile( WIpath, DCpath,CCpath )
        evt.SetFilterHSChopperMode()
        evt.SetHistAllocation()

        if (starttime<0.0) and (endtime<0.0):
            pass
        else:
            evt.SetRangeOfSingleTimeSlicing(starttime,endtime)

        evt.LoadEventDataFiles( runnumber, datapath, t0datapath )
        DAT=mm.ElementContainerMatrix()
        evt.SetElementContainerMatrix( DAT, 1 )
        ## not use trignet use fast chopper -end
    elif useTrignet==1 or useTrignet==2 or useTrignet==3:
        ## use trignet -start

        evt.LoadParamFiles( WIpath, DCpath, CIpath )
        evt.LoadChopCondFile( WIpath, DCpath,CCpath )

        #evt.LoadTrignetChopFile( runnumber, "/data/DNA", t0datapath )
        evt.LoadTrignetChopFile( runnumber, datapath, t0datapath )
        evt.LoadTrignetEventFile( runnumber, datapath, t0datapath )
        evt.SetHistAllocation()

        if (starttime<0.0) and (endtime<0.0):
            pass
        else:
            evt.SetRangeOfSingleTimeSlicing(starttime,endtime)

        evt.LoadEventDataFiles( runnumber, datapath, t0datapath )
        DAT=mm.ElementContainerMatrix()
        evt.SetElementContainerMatrix( DAT, 1 )
        ## use trignet -end
    else:
        ## original not use trignet -start
        evt.LoadParamFiles( WIpath, DCpath )
        ##[inamura 180911]-->
        lambda_info_list = ChopCondInfo_xml.split(",")
        evt.SetLambdaParam(float(lambda_info_list[0]), float(lambda_info_list[1]))
        print(("## [inamura 180911] EventDataToEcm >> lambda params = ",float(lambda_info_list[0]), float(lambda_info_list[1])))
        ##<--[inamura 180911]
        evt.SetHistAllocation()

        if (starttime<0.0) and (endtime<0.0):
            pass
        else:
            evt.SetRangeOfSingleTimeSlicing(starttime,endtime)

        DAT = mm.ElementContainerMatrix()
        evt.SetElementContainerMatrix( DAT, runnumber, datapath, t0datapath )
        ## original not use trignet -end



    ##[inamura 180925]-->
    if mu.UTSUSEMIMANYOVERSION>'0.3.6':
        #URI=mu.UtsusemiReductionInEla(DAT)
        #URI.CalcPhi(Def_Pixel_Size[0],Def_Pixel_Size[1],Def_Pixel_Size[2])
        #del URI
        pass
    else:
        Phi=mu.PhiCalculation(DAT,Def_Pixel_Size[0],Def_Pixel_Size[1],Def_Pixel_Size[2])
        Phi.CalcPhi()
        del Phi
    ##<--[inamura 180925]
    
    ##[inamura 160227]-->
    import math
    for i in range( DAT.PutSize() ):
        for j in range( DAT(i).PutSize() ):
            hh = DAT(i,j).PutHeaderPointer()
            if (hh.CheckKey("PolarAngle")==1):
                pol_DNA = hh.PutDouble("PolarAngle")
                azm_DNA = hh.PutDouble("AzimAngle")
                ##[inamura 180925]-->
                if mu.UTSUSEMIMANYOVERSION>'0.3.6':
                    pol_v = mm.MakeDoubleVector(2)
                    pol_v[1]=0.0
                    azm_v = mm.MakeDoubleVector(2)
                    azm_v[1]=0.0
                else:
                    pol_v = hh.PutDoubleVector("PixelPolarAngle")
                    azm_v = hh.PutDoubleVector("PixelAzimAngle")
                    hh.Erase("PixelPolarAngle")
                    hh.Erase("PixelAzimAngle")

                pol_v[0] = pol_DNA/math.pi*180.0  # [rad]->[degree]
                azm_v[0] = azm_DNA/math.pi*180.0  # [rad]->[degree]
                ##<--[inamura 180925]

                hh.Add("PixelPolarAngle", pol_v )
                hh.Add("PixelAzimAngle", azm_v )

            if not isHistogram: ##[inamura 170616]
                hh.Add("isHistogram",0)
                
        if not isHistogram: ##[inamura 170616]
            hh_eca = DAT(i).PutHeaderPointer()
            hh_eca.Add("isHistogram",0)
    
    if not isHistogram: ##[inamura 170616]
        hh_ecm = DAT.PutHeaderPointer()
        hh_ecm.Add("isHistogram",0)
        
    ##<--[inamura 160227]

    del evt

    return DAT

