import Manyo as mm
import Manyo.Utsusemi as mu
import os

from ana.Reduction.DefaultInstParams import *   #[inamura 120807]

__version__ = "0.7"

def GetHistogram(eventtype="PSD",runnumber=[],
                 WiringInfo_xml="WiringInfo.xml",
                 DetectorInfo_xml="DetectorInfo.xml",
                 starttime=-1.0, endtime=-1.0,
                 withPH=False):
    """
    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 withPH (bool) make histogram with pulse height info
    @retval DAT        ElementContainerMatrix
    """
    if type(runnumber)==type(0):
        runnumber = [runnumber]
    elif type(runnumber)==type([]):
        pass
    else:
        msg = "EventDataToEcm >> runnumber parameter is invalid."
        raise UserWarning,msg
    runnumbers = mm.MakeUInt4Vector()
    for a_run in runnumber:
        runnumbers.push_back( int(a_run) )
    
    evt = None
    if eventtype=="PSD" or eventtype=="N2MON":
        if withPH:
            evt = mu.UtsusemiEventDataConverterNeunetWithPH()
            if eventtype=="N2MON":
                evt.SetIsGateNet( True )
            else:
                evt.SetIsGateNet( False )
        else:
            evt = mu.UtsusemiEventDataConverterNeunet()
    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["UTSUSEMI_USR_PRIV_HOME"],"ana","tmp")
    
    #st_runno="%06d" % runnumber
    if os.environ.has_key("UTSUSEMI_USR_PRIV_HOME"):
        WIpath=os.path.join(os.environ["UTSUSEMI_USR_PRIV_HOME"],"ana","xml",WiringInfo_xml)
    elif os.environ.has_key("HOME"):
        WIpath=os.path.join(os.environ["HOME"],"ana","xml",WiringInfo_xml)
    else:
        WIpath=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)
        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)
    
    print CommentHead+"WiringInfo path=",WIpath
    print CommentHead+"DetectorInfo path=",DCpath


    evt.LoadParamFiles( WIpath, DCpath )
    evt.SetHistAllocation()

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

    DAT = mm.ElementContainerMatrix()
    evt.SetElementContainerMatrix( DAT, runnumbers, datapath, t0datapath )

    Phi=mu.PhiCalculation(DAT,Def_Pixel_Size[0],Def_Pixel_Size[1],Def_Pixel_Size[2])
    Phi.CalcPhi()
    
    del evt
    del Phi
    
    return DAT
