#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import print_function
import os
import math
import Manyo as mm
import Manyo.Utsusemi as mu
import re
##########################################

def SliceQE(dat,lowerQ,upperQ):
    """
    SliceQE

    @param dat    (ElementContaienrArray)
    @param lowerQ    (double) lowerQ
    @param upperQ    (double) upperQ

    @retval ec    (ElementContainer)
    """
    QE = mu.AdvSliceQE()
    ec = QE.Slice(dat,lowerQ,upperQ)
    hh=ec.PutHeader()
    #NumOfMask = hh.PutInt4("NumOfMask")
    #NumOfEC = hh.PutInt4("NumOfOrigEC")
    #print NumOfMask,NumOfEC 
    return ec

##########################################

def SliceQEall(dat,initialQ,finalQ,deltaQ):
    """
    SliceQEall

    @param dat    (ElementContaienrArray)
    @param initialQ  (double)
    @param finalQ    (double)
    @param deltaQ    (double)

    @retval eca    (ElementContainerArray)
    """

    QE = mu.AdvSliceQE()
    h=dat.PutHeader()
    eca = mm.ElementContainerArray()
    Xrange = dat(0).PutHeaderPointer().PutDoubleVector("XRANGE")
    if deltaQ < (Xrange[1]-Xrange[0]):
         deltaQ = (Xrange[1]-Xrange[0])
         print("deltaQ is set",str(deltaQ))
    num = int ( float(finalQ-initialQ)/deltaQ )
    for i in range(num):
         lowerQ = initialQ+deltaQ*i
         upperQ = initialQ+deltaQ*(i+1)
         ec = QE.Slice(dat,lowerQ,upperQ)
         hh = ec.PutHeader()
         hh.Add("lowerQ",lowerQ)
         hh.Add("upperQ",upperQ)
         #NumOfMask = hh.PutInt4("NumOfMask")
         #NumOfEC = hh.PutInt4("NumOfOrigEC")
         #Total   = hh.PutDouble("TotalCounts")
         #print NumOfMask,NumOfEC,Total
         ec.InputHeader(hh)
         eca.Add(ec)
    eca.InputHeader(h)
    return eca

##########################################

def SliceQEbyText(dat,Q_list_string):
    """
    SliceQEall

    @param dat    (ElementContaienrArray)
    @param Q_list_string         (string)
    @retval eca    (ElementContainerArray)
    """

    QE = mu.AdvSliceQE()
    eca = mm.ElementContainerArray()
    h=dat.PutHeader()
    if type(Q_list_string)==str:
        Q_list = Q_list_string.split(",")
    elif type(Q_list_string)==list:
        Q_list = Q_list_string

    Q_list_size = len(Q_list)

    for i in range(Q_list_size-1):
        lowerQ = float(Q_list[i])
        upperQ = float(Q_list[i+1])
        ec = QE.Slice(dat,lowerQ,upperQ)
        hh = ec.PutHeader()
        hh.Add("lowerQ",lowerQ)
        hh.Add("upperQ",upperQ)
        #NumOfMask = hh.PutInt4("NumOfMask")
        #NumOfEC = hh.PutInt4("NumOfOrigEC")
        ec.InputHeader(hh)
        eca.Add(ec)
    eca.InputHeader(h)
    return eca

#########################################

def OutputPartOfEC(ec,initial,final):
    """
    OutputPartOfEC

    @param ec         (ElementContaienr)
    @param initial    (double)
    @param final      (double)
    @retval EC        (ElementContainer)
    """
    xbin=ec.PutX()
    ybin=ec.PutY()
    ebin=ec.PutE()

    xbin_new =[]
    ybin_new =[]
    ebin_new =[]

    nmin=0
    nmax=0
    if (initial < xbin[0]):
        initial = xbin[0]
    if (final > xbin[len(xbin)-1]):
        final = xbin[len(xbin)-1]

    for i in range(len(xbin)):
        if(initial > xbin[i]):
            nmin += 1
        if(final >= xbin[i]):
            nmax += 1

    for i in range(nmin,nmax):
        xbin_new.append(xbin[i])
        ybin_new.append(ybin[i])
        ebin_new.append(ebin[i])
    xbin_new.append(xbin[nmax])

    EC = mm.ElementContainer()
    EC.Add("x",xbin_new)
    EC.Add("y",ybin_new)
    EC.Add("e",ebin_new)
    EC.SetKeys("x","y","e")

    return EC

#########################################

def OutputPartOfECA(ecaDet,initial,final):
    """
    OutputPartOfEC

    @param ecaDet     (ElementContaienrArray)
    @param initial    (double)
    @param final      (double)
    @retval ECA       (ElementContainerArray)
    """
    eca_out = mm.ElementContainerArray()
    num=ecaDet.PutSize()
    for i in range(num):
        ec = OutputPartOfEC(ecaDet.Put(i),initial,final)
        hh=ecaDet.Put(i).PutHeader()
        ec.InputHeader(hh)
        eca_out.Add(ec)

    return eca_out

#########################################

def OutputECBinning(ec,initial,final,delta):
    """
    OutputECBinng

    @param ec         (ElementContaienr)
    @param initial    (double)
    @param final      (double)
    @param delta      (double)
    @retval EC        (ElementContainer)
    """
    xbin_new =[]

    if initial > final:
        num_tmp = initial
        initial = final
        final = num_tmp

    xbin_num = int(math.ceil(abs(final-initial)/delta))+1

    for i in range(xbin_num):
        xbin_new.append(i*delta + initial)

    xbin_newVec = mm.ListToDoubleVector(xbin_new)

    EC = ec.Binning(xbin_newVec)

    return EC

#########################################

def OutputECABinning(eca,initial,final,delta):
    """
    OutputECBinng

    @param eca        (ElementContaienrArray)
    @param initial    (double)
    @param final      (double)
    @param delta      (double)
    @retval EC        (ElementContainer)
    """

    num_of_ec = eca.PutSize()
    ECA= mm.ElementContainerArray()

    xbin_new =[]

    if initial > final:
        num_tmp = initial
        initial = final
        final = num_tmp

    xbin_num = int(math.ceil(abs(final-initial)/delta))+1

    for i in range(xbin_num):
        xbin_new.append(i*delta + initial)

    xbin_newVec = mm.ListToDoubleVector(xbin_new)

    for i in range(num_of_ec):
        EC = eca(i).Binning(xbin_newVec)
        ECA.Add(EC)

    return ECA

#########################################

def DoQEMask(ECA,filename="QEMask.txt"):
    """
    Mask QE grape , AS
    @param eca (ElementContainerArray)
    @param filename (string)
    @retval None
    """
    filepath = os.path.join(os.environ["MLF_USR_DIR"],"ana","xml",filename)
    f=open(filepath)
    #ECA = ReadECA("ECA_654_QE.bst")
    lines = f.readlines()
    f.close()

    lower=[]
    upper=[]

    for line in lines:
        comment = re.search("#", line)
        if not (comment):
            if re.search("\n", line):
                line = line.split("\n")[0]
            flug1 = re.search(",", line)
            if flug1:
                if float(line.split(",")[0]) > float(line.split(",")[1]):
                    lower.append(line.split(",")[1])
                    upper.append(line.split(",")[0])
                elif float(line.split(",")[1]) >= float(line.split(",")[0]):
                    lower.append(line.split(",")[0])
                    upper.append(line.split(",")[1])

    numOfQ = ECA.PutSize()
    Qmask = []
    x = []

    for j in range(numOfQ):
        hh = ECA(j).PutHeader()
        Xrange = hh.PutDoubleVector("XRANGE")
        XrangeCenter = (Xrange[0]+Xrange[1])*0.5
        mask = 0
        for i in range(len(lower)):
            if (XrangeCenter >= float(lower[i])) and (XrangeCenter < float(upper[i])):
                mask = 1
        hh.OverWrite("MASKED",mask)
        ECA(j).InputHeader(hh)

