from __future__ import print_function
import Manyo as mm
import math
#ttt
def TimeFocusDNA(eca, T0Shift, sd, ed, dbin, FastChopperUse = True):
    
    LSample = 42.0
    LFC = 7.725

    if (FastChopperUse):
        L1 = LSample-LFC
    else:
        L1 = LSample
    
    toflist = []
    ylist = []
    elist = []
    cntnumlist = []

    toflist.append(sd)
    while 1:
        toflist.append(toflist[-1]+dbin)
        ylist.append(0)
        elist.append(0)
        cntnumlist.append(0)
        
        if  toflist[-1] >= ed:
            break

    TOFbinNum = len(toflist)-1
    
    ecanew = mm.ElementContainerArray()
    ecanew.InputHeader(eca.PutHeaderPointer())

    for ii in range(eca.PutTableSize()):
        if ii % 100 ==0:
            print("%d / %d" %(ii,eca.PutTableSize()))
        
        ec = eca.Put(ii)
        ecnew = mm.ElementContainer()
        ecnew.InputHeader(ec.PutHeaderPointer())
        
        temptof = ec.PutXList()
        tempy = ec.PutYList()
        tempe = ec.PutEList()
        invL12 = 1.0/(GetL2(ec)+L1)
        pa = invL12/math.sin(GetPolerAngle(ec)*0.5)
        d = 0.0
        for jj in range(len(ylist)):
            ylist[jj] = 0.0
            elist[jj] = 0.0

        for jj in range(len(tempy)):
            d = 1.97801e-3*pa*((temptof[jj]+temptof[jj+1])/2-T0Shift)
            pp = int((d-sd)//dbin)
            """ 
            if ii == 325:
                print pp, len(ylist),(1.97801e-3*pa*((temptof[jj]+temptof[jj+1])/2-T0Shift)),d
            """
            if pp >=0 and pp <TOFbinNum:
                ylist[pp] += tempy[jj]
                elist[pp] = math.sqrt(elist[pp]**2+tempe[jj]**2)
            #else:
                #print pp, ii, jj

        ecnew.Add("TOF",toflist)
        ecnew.Add("Intensity", ylist)
        ecnew.Add("Error",elist)
        ecnew.SetKeys("TOF","Intensity","Error")

        ecanew.Add(ecnew)

    return ecanew

def GetL2(ec):
    pixpos = ec.PutHeader().PutDoubleVector("PixelPosition")
    #print len(pixpos)
    L2 = 0.0
    for ii in range(len(pixpos)):
        L2 += pixpos[ii]**2

    return math.sqrt(L2)/1000

def GetPolerAngle(ec):
    pixpa =  ec.PutHeader().PutDoubleVector("PixelPolarAngle")
    return pixpa[0]*math.pi/180.0
