from __future__ import print_function
import time,sys,os,math
import Manyo as mm
import Manyo.Utsusemi as mu
import uGao.MPlot as mp


ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
if ver<2.5:
    from elementtree.ElementTree import ElementTree
else:
    from xml.etree.ElementTree import ElementTree

def GetECPeakInfo(ec,note,emin,emax,delta_bin,):
    """
    @param ec       (ElementContainer)
    @param note     (string)
    @param emin     (float)
    @param emax     (float)
    @param delta_bin     (int)
    @retval result
    """
    import datetime as dt
    xbin = ec.PutX()
    ybin = ec.PutY()
    ebin = ec.PutE()

    xbin_min = 0
    xbin_max = 0
    sum_val = 0
    sum_val_e = 0
    sum_val_e2 = 0
    net_val = 0
    net_val_e = 0

    back_val1_buf = 0
    back_val1_e2 = 0
    back_val2_buf = 0
    back_val2_e2 = 0

    back_val = 0
    back_val_e = 0

    ymax = 0
    ymax_i=0
    y_back = 0
    y_back_e = 0

    ymax_mean_buf=0
    ymax_mean=0
    ymax_mean_e2=0
    ymax_mean_e=0

    fwhm=0
    fwhm_e=0

    for i in range(len(xbin)):
        if xbin[i] < emin:
                xbin_min = i + 1
        if xbin[i] < emax:
                xbin_max = i + 2
 
    for i in range(xbin_min,xbin_max):
        sum_val += ybin[i]
        sum_val_e2 += ebin[i]*ebin[i]
        if ymax<ybin[i]:
             ymax=ybin[i]
             ymax_i=i
    sum_val_e = math.sqrt(sum_val_e2)
    for i in range(ymax_i - delta_bin , ymax_i + delta_bin):
        ymax_mean_buf += ybin[i]
        ymax_mean_e2 += ebin[i]*ebin[i] 

    ymax_mean = ymax_mean_buf/(delta_bin*2)
    ymax_mean_e = math.sqrt(ymax_mean_e2)/(delta_bin*2)

    for i in range(xbin_min - delta_bin , xbin_min + delta_bin):
        back_val1_buf += ybin[i]
        back_val1_e2 += ebin[i]*ebin[i]
    for i in range(xbin_max - delta_bin , xbin_max + delta_bin):
        back_val2_buf += ybin[i]
        back_val2_e2 += ebin[i]*ebin[i]

    y_back = (back_val1_buf + (back_val2_buf - back_val1_buf)/(xbin_max-xbin_min)*(ymax_i-xbin_min))/(delta_bin*2)
    y_back_e = (math.sqrt(back_val1_e2) + math.sqrt(back_val1_e2+back_val2_e2)/(xbin_max-xbin_min)*(ymax_i-xbin_min))/(delta_bin*2)

    back_val = (back_val1_buf+back_val2_buf)/(delta_bin*4)*(xbin_max-xbin_min)
    back_val_e = math.sqrt(back_val1_e2+back_val2_e2)/(delta_bin*4)*(xbin_max-xbin_min)

    net_val = sum_val - back_val
    net_val_e = math.sqrt(sum_val_e2 + back_val_e * back_val_e)

    peak_intenisity = ymax_mean -y_back
    peak_intenisity_e = math.sqrt(ymax_mean_e*ymax_mean_e + y_back_e*y_back_e)

    fwhm = net_val/peak_intenisity/math.sqrt(2*math.pi)*2*math.sqrt(2*math.log(2))*(xbin[1]-xbin[0])
    fwhm_e = net_val/peak_intenisity *math.sqrt((net_val_e**2)/(net_val**2) + (peak_intenisity_e**2)/(peak_intenisity**2))/math.sqrt(2*math.pi)*2*math.sqrt(2*math.log(2))*(xbin[1]-xbin[0])

    print("")
    print("////////////////////////////////////////////")
    print("///    Integral Counting result          ///")
    print("xbin start     = %.2f"%(emin))
    print("xbin end       = %.2f"%(emax))
    print("peak intensity = %.2e, error = %.2e"%(ymax_mean,ymax_mean_e))
    print("gross count    = %.2e, error = %.2e"%(sum_val,sum_val_e))
    print("back count     = %.2e, error = %.2e"%(back_val,back_val_e))
    print("net count      = %.2e, error = %.2e"%(net_val,net_val_e))
    print("fwhm           = %.2e, error = %.2e"%(fwhm,fwhm_e))
    print("////////////////////////////////////////////")

    result = []

    result.append(ymax_mean)
    result.append(fwhm)
    result.append(y_back)

    day=dt.datetime.now()

    filename = "PeakInfo"+str(day.year)+"_"+str(day.month)+"_"+str(day.day)+".txt"
    #filepath = os.path.join(os.environ["HOME"],"ana","tmp",filename)
    filepath = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","tmp",filename)
    flug = os.path.exists(filepath)

    if flug == False:
        fw = open(filepath, 'w')
        fw.write('time\tNo\txbin_start\txbin_end\tpeak_intensity\terror\tgross_count\terror\tback_count\terror\tnet_count\terror\tFWHM\terror\tnote\n')
        line_num=1
    else:
        fr = open(filepath, 'r')
        line_num = len(fr.readlines())
        fr.close()
        fw = open(filepath, 'a')

    fw.write(str(day.hour)+":"+str(day.minute)+":"+str(day.second))
    fw.write("\t%.i\t%.2f\t%.2f\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t"%(line_num,emin,emax,ymax_mean,ymax_mean_e,sum_val,sum_val_e,back_val,back_val_e,net_val,net_val_e,fwhm,fwhm_e))
    fw.write(note+"\n")  
    fw.close()

    return ymax_mean,fwhm,y_back

def GetECPeakIntegral(ec,emin,emax):
    """
    @param ec       (ElementContainer)
    @param emin     (float)
    @param emax     (float)
    @retval result
    """
    xbin_min = 0
    xbin_max = 0
    sum_val = 0
    sum_val_e = 0
    sum_val_e2 = 0

    xbin = ec.PutX()
    ybin = ec.PutY()
    ebin = ec.PutE()

    if emin>emax:
        e_buf=emin
        emin=emax
        emax=e_buf

    for i in range(len(xbin)):
        if xbin[i] < emin:
                #xbin_min = i + 1
                xbin_min = i   # 2012/07/12 modify
        if xbin[i] < emax:
                #xbin_max = i + 2
                xbin_max = i   # 2012/07/12 modify

    for i in range(xbin_min,xbin_max):
        sum_val += ybin[i]
        sum_val_e2 += ebin[i]*ebin[i] 

    sum_val_e = math.sqrt(sum_val_e2)

    return sum_val,sum_val_e
