from __future__ import print_function
import utsusemi.ana.Reduction.EditWiringFile as ED
import math
import os

class EditWiringInfoForGUI:
    
    def __init__(self,filename,type_, pmin, pmax, pbin, Lambda,LambdaWidth):

        self.ed = ED.EditWiringInfo(filename)
        self.Type = type_
        self.params = []
        self.params.append(pmin)
        self.params.append(pmax)
        self.params.append(pbin)
        self.Lambda = Lambda
        self.LambdaWidth = LambdaWidth
        self.L12 = 44.1 #L1 = 42m, L2 = 2.1m

    #dfile = "/home/dnaadmin/dev/Diffraction/FB/DetectorInfoTYMM20140120.xml"
    
    def SetTofBinPattern(self):
        if(self.Type == 22):
            self.params.append(0.0)
            self.params.append(0.0)
            self.params.append(1.0)

        self.ed.change_TofBinPattern(0,self.Type,self.params)
    
    def SetFrameInfo(self):
        Lambdamin = self.Lambda-self.LambdaWidth*0.5
        Tofmin = 252.8*Lambdamin*self.L12

        Lambdamax = self.Lambda+self.LambdaWidth*0.5
        Tofmax = 252.8*Lambdamax*self.L12
        
        if math.ceil(Tofmin/40000) == math.ceil(Tofmax/40000) :
            boundary = 0.0
        else:
            boundary = math.fmod(Tofmin, 40000)

        frameNo = math.ceil(Tofmax / 40000)
        #boundary = Tofmin % 40000.0

        print("DiffractionGUIMain >>", Tofmin, Tofmax, frameNo, boundary)

        self.ed.set_FrameInfo(frameNo,boundary)

    def OutputXml(self):
        self.SetTofBinPattern()
        self.SetFrameInfo()

        NewWIfilename = "WiringInfoGUItemp.xml"
        self.ed.SaveToXml(NewWIfilename)

        return os.path.join(os.getcwd(),NewWIfilename)
        


