from __future__ import print_function
#TOF_RESOLVER1 = 89770.0
#TOF_RESOLVER1 = 87770.0 #89770.0 - 50(TOF offset)*40
TOF_RESOLVER1 = 89770.0/40.0-40
#TOF_RESOLVER1 = 0.0

#TOF_RESOLVER2 = 90636.4
#TOF_RESOLVER2 = 88636.4 #90636.4 - 50(TOF offset)*40
#TOF_RESOLVER2 = 90636.4/40.0
TOF_RESOLVER2 = 0.0
import os
#import SetError as SE
import datetime
import Com
import Manyo as mm
import utsusemi.vis.VisualModuleQBase as UVM
#-----------------------------------------------------------------------------------------
def command(runNos, offsets, timeRanges, hwParam, lambdaParam, tofSource,
            startQ, endQ, deltaQ, slitwidths, useTrignets, fChop, maskInfoPath, effInfoPath):
    try:
        t1 = datetime.datetime.now()
        #import vis.M2Plot as m2p
        #import Manyo as mm
        import Cmm
        #offsets      = [-600,-420,-240,-60,120]
        #runNos       = [1965,1963,1959,1962,1966]
        #timeRanges   = ["-1.0/-1.0","-1.0/-1.0","-1.0/-1.0","-1.0/-1.0","-1.0/-1.0"]

        #hwParam      = "0.001/-0.4/0.4"
        #hwParam      = "-0.4,-0.3,-0.2,-0.1,0.0,0.1,0.2,0.3,0.4"
        #bins=[str(k*0.002 -0.4) for k in range(400)]
        #hwParam=",".join(bins)

        #lambdaParam  = "6.321/4.15"
        #tofSource    = "120/320"

        #startQ = 0.0
        #endQ   = 1.0
        #deltaQ = 0.02

        useT0ModCorr = False
        background   = 0.0
        useMonEff    = True
        
        ecms=[]
        Logformat = "{0:<9}{1:^25}{2:^17}{3:^13}\n"
        LogText = Logformat.format("Run No","timeRange", "tofSource", "useTrignet")
        print(LogText)
        ii = 0
        for runNo,offset,timeRange,slitwidth,useTrignet \
                                     in zip(runNos,offsets,timeRanges,slitwidths,useTrignets):

            if slitwidth==1:
                #slitwidth = -1
                slitwidth = 3
            elif slitwidth==0:
                slitwidth = 1
            else:
                slitwidth = -1

            if useTrignet:
                if runNo > 10511:#[TY Modified 20190409]
                    TOF_RESOLVER1=2246.9*225.0/float(fChop)

                offset = str(offset)+","+str(TOF_RESOLVER1)+","+str(TOF_RESOLVER2)
            else:
                #offset = "0.0,"+str(offset)
                #TY modified[20160427]
                t0shift = float(offset)-1.5/float(fChop)*1.0e6
                print(t0shift)
                offset = "0.0,%f" %(t0shift)
                print(offset)
                #offset = "0.0,"+str(offset-1.5/fChop*1.0e6)

            slitinfo = str(slitwidth)+"/"+str(fChop)
            print("koko67 command.py Monitor Start", runNo)
            if useTrignet:
                monec = Cmm.GetHistogramMonETrignet(runNo, str(lambdaParam), str(offset),
                                                    background, useT0ModCorr,
                                                    str(timeRange), str(tofSource), str(slitinfo))
#                                                    str(timeRange), "0/400", str(slitinfo))
            else:
                monec = Cmm.GetHistogramMonEnoTrignet(runNo, lambdaParam, offset,
                                                      background, useT0ModCorr,
                                                      timeRange, tofSource, slitinfo)
            print("koko77 command.py Monitor End", runNo)

            #Cmm.MutiplyConstant(monec, 1e-09)

            print("koko81 command.py Inela Start", runNo)
            if useTrignet:
                psdecm = Cmm.GetHistogramHWTrignet(runNo, hwParam, lambdaParam,
                                                   offset, useT0ModCorr,
                                                   timeRange, tofSource, slitinfo)
            else:
                psdecm = Cmm.GetHistogramHWnoTrignet(runNo, hwParam, lambdaParam,
                                                     offset, useT0ModCorr,
                                                     timeRange, tofSource, slitinfo)
                print(runNo, hwParam, lambdaParam, offset, useT0ModCorr,timeRange, tofSource, slitinfo)
            if maskInfoPath!="":
                #psdecm=SE.SetError(psdecm)
                maskInfoPath = str(os.path.basename(maskInfoPath))
                Cmm.DoMask(psdecm, maskInfoPath)
            print("koko95 command.py Inela end", runNo)
            #print "-->before"
            #psdecm.Put(40).Put(50).Dump()
            #Cmm.DoMaskForEachEC(psdecm)
            #print "-->after"
            #psdecm.Put(40).Put(50).Dump()
            LogText += Logformat.format(runNo, timeRange, tofSource, useTrignet)
            if ii == 0:
                ecsum = monec
                psdsum = psdecm
            else:
                print("--> Sum ec and psdecm start")
                ecsum = Com.ExecFunctionCode(Code="A+B",A=ecsum,B=monec)
                psdsum = Com.CalcContainers(dat1=psdsum,dat2=psdecm,coef1=1.0,coef2=1.0,ope="+")
                print("--> Sum ec and psdecm end")
            ii += 1
        #print "psdsum -->"
        #psdsum.Put(40).Put(50).Dump()
        ecm2 = Cmm.ILambdaCorrDNA(psdsum, ecsum, useMonEff)
        #print "ecm2--->"
        #ecm2.Put(40).Put(50).Dump()
        effInfoPath = str(effInfoPath)
        if effInfoPath!="":
            ecm3 = Cmm.SolidAngleCorrDNA(ecm2, True, False, True, "sample", DetEffDataPath = effInfoPath)
        else:
            ecm3 = Cmm.SolidAngleCorrDNA(ecm2, True, False, False, "sample")
        del ecm2
        Cmm.KiKfCorrection(ecm3) #TYAdd[20150910]
        Cmm.MutiplyConstant(ecm3, 1e3)
        
        ecaQE = Cmm.CreateQEMap(ecm3,startQ,endQ,deltaQ)
        footer = "_AMDRQE"
        Cmm.OutputECA( ecaQE, footer)
        """
        if len(ecms)>1:
            footer = "_mAMDRQE"
        """
        hwlist = []
        hwlist = hwParam.split(",")
        if len(hwlist) !=3:
            print("koko3")
            Cmm.OutputNeiECAText(ecaQE,"_neimAMDRQE")
        
        Cmm.OutputECAText( ecaQE, footer)
        Cmm.OutputECADAVEText( ecaQE, footer)
        del ecms
        del ecm3
        #Cmm.OutputECM( ecm3,footer+"ECM3")

        print(LogText)
        print("Needed time is ", (datetime.datetime.now() - t1).seconds , "s.") #TY add[20151119]
        showdat(ecaQE)
#        showdat(ecsum)
        #m2p.M2Plot(ecaQE)
        #Cmm.DoMaskForEachEC(psdecm)
        #psdecm.Put(5).Put(50).Dump()

        
    except:
        print("import Error / Manyo, MPlot")
#-----------------------------------------------------------------------------------------

def showdat(dat):
    if type(dat) ==type(mm.ElementContainer()):
        #MP.MPlot(dat)
        UVM.MPlot(dat)
    elif type(dat) == type(mm.ElementContainerArray()):
        #MP2.M2Plot(dat)
        UVM.M2PlotPlus(dat)
    else:
        print("dat type is not EC or ECA.")


