#! /usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
import time
import os
import sys
import Cmm
import uGao.MPlot as MP
import uGao.M2PlotPlusCui as MP2
import utsusemi.DNA.MultiDataCombine.subUtils.BinInfoReaderBase as MDCR
import EneOrig
import subprocess
import Manyo.Utsusemi as MU

PYSIDEVER = 6
try:
    from PySide6 import QtCore, QtGui, QtWidgets
    from PySide6.QtWidgets import QApplication, QFileDialog, QListWidgetItem, QMessageBox
    from PySide6.QtCore import QFile
    from ui6_SQW import Ui_MainWindow
except:
    from PySide2 import QtCore, QtGui, QtWidgets
    # from PySide2.QtUiTools import QUiLoader
    from PySide2.QtWidgets import QApplication, QFileDialog, QListWidgetItem, QMessageBox
    from PySide2.QtCore import QFile
    from ui2_SQW import Ui_MainWindow
    PYSIDEVER = 2


class App(QtWidgets.QMainWindow):
    def __init__(self, master = None):
        super(App, self).__init__(master)
        self.frame = Ui_MainWindow()
        self.frame.setupUi(self)

        self.errorstr = self.frame.errorstr
        
        """
        self.lam =
        self.dl =
        self.emin =
        self.emax =
        self.de =
        self.cb_UserDefinedEBin =  # => self.Ebin_flag
        self.bt_UserDefinedEBin =  # button5
        self.cb21_3 = # "txt_EbinFileName" <- self.cb21_3  => self.EbinFile_name
        self.T0S =
        self.Sta =
        self.End =
        self.cb_VanadiumCorr =  # => self.DetEffCr_flag
        self.bt_VanadiumCorr = # button4
        self.txt_VanadiumCorr = # => self.DetEffFile_name
        self.bt_MaskFile = 
        #self.txt_MaskFile = 
        self.cb41 = self.frame.txt_MaskFile # => self.MaskFile_name = "maskTY.txt"
        """
        
        
        if ( FastChopperUse == True):
            #self.setStyleSheet("background-color: lime")
            self.frame.background.setStyleSheet("background-color: lime")
            #tkinter.Frame.__init__(self, master, background="#2DE56B")
            #self.master.title("DNA SQW Reduction With Fast Chopper")
            self.setWindowTitle("DNA SQW Reduction With Fast Chopper")
            #self.errorstr = tkinter.StringVar()
            #self.errorstr.set("High Resolution Mode.")
            self.errorstr.setText("High Resolution Mode.")
        else:
            #tkinter.Frame.__init__(self, master)
            #self.master.title("DNA SQW Reduction Without Fast Chopper")
            self.setWindowTitle("DNA SQW Reduction Without Fast Chopper")
            #self.errorstr = tkinter.StringVar()
            #self.errorstr.set("Low Resolution Mode.")
            self.errorstr.setText("Low Resolution Mode.")

        # Si(111) self.si == 0, Si(333) self.si == 1
        self.si = 0
        #self.v = tkinter.IntVar()

        #display = tkinter.Label(self, textvariable = self.errorstr, font = ('Helvetica', '16', 'bold'))
        #display.pack( side = tkinter.TOP)
        #f0 = tkinter.LabelFrame(self, text = 'Si')
        #f01 = tkinter.LabelFrame(f0, relief = tkinter.FLAT)
        #self.v.set(0)
        #rd = tkinter.Radiobutton(f01, text = 'Si(111) : dQ=', value = 0, variable = self.v, command = self.sel_si)
        #rd.pack(padx=2, pady=2)
        #rd = tkinter.Radiobutton(f01, text = 'Si(333) : dQ=', value = 1, variable = self.v, command = self.sel_si)
        #rd.pack(padx=2, pady=2)
        #rd = tkinter.Radiobutton(f01, text = 'Si(311) : dQ=', value = 2, variable = self.v, command = self.sel_si)
        #rd.pack(padx=2, pady=2)
        #f01.pack(padx=0,pady=2, side = tkinter.LEFT)
        #f02 = tkinter.LabelFrame( f0, relief = tkinter.FLAT)

        self.frame.rb_Si111.clicked.connect(self.sel_si)
        self.frame.rb_Si333.clicked.connect(self.sel_si)
        self.frame.rb_Si311.clicked.connect(self.sel_si)
        self.rb_group = QtWidgets.QButtonGroup()
        self.rb_group.addButton(self.frame.rb_Si111, 1)
        self.rb_group.addButton(self.frame.rb_Si333, 2)
        self.rb_group.addButton(self.frame.rb_Si311, 3)
        self.v = 0
        self.rb_group.button(self.v + 1).setChecked(True)

        #f021 = tkinter.LabelFrame( f02, relief = tkinter.FLAT)
        #self.dqs1 = tkinter.Spinbox( f021, from_=0.01, to=9.99, increment=0.01, width=4, format='%4.2f')
        #self.dqs1.delete( 0, tkinter.END)
        #self.dqs1.insert( 0, '0.05')
        #self.dqs1.pack(padx=0,pady=0, side = tkinter.LEFT)
        #rd = tkinter.Label(f021, text = " Qmin=0.0 Qmax=2.0")
        #rd.pack(padx=0,pady=0, side = tkinter.LEFT)
        #f021.pack(padx=0,pady=2, fill = tkinter.BOTH)
        self.dqs1 = self.frame.dsp_Si111
        self.dqs1.setMaximum(9.99)
        self.dqs1.setMinimum(0.01)
        self.dqs1.setSingleStep(0.01)
        self.dqs1.setValue(0.05)

        #f022 = tkinter.LabelFrame(f02, relief = tkinter.FLAT)
        #self.dqs3 = tkinter.Spinbox( f022, from_=0.01, to=9.99, increment=0.01, width=4, format='%4.2f')
        #self.dqs3.delete( 0, tkinter.END)
        #self.dqs3.insert( 0, '0.10')
        #self.dqs3.pack(padx=0,pady=0, side = tkinter.LEFT)
        #rd = tkinter.Label( f022, text = " Qmin=0.0 Qmax=6.0")
        #rd.pack(padx=0,pady=0, side = tkinter.LEFT)
        #f022.pack(padx=0,pady=2, fill = tkinter.BOTH)
        self.dqs3 = self.frame.dsp_Si333
        self.dqs3.setMaximum(9.99)
        self.dqs3.setMinimum(0.01)
        self.dqs3.setSingleStep(0.01)
        self.dqs3.setValue(0.05)

        #f023 = tkinter.LabelFrame(f02, relief = tkinter.FLAT)
        #self.dqs4 = tkinter.Spinbox( f023, from_=0.01, to=9.99, increment=0.01, width=4, format='%4.2f')
        #self.dqs4.delete( 0, tkinter.END)
        #self.dqs4.insert( 0, '0.10')
        #self.dqs4.pack(padx=0,pady=0, side = tkinter.LEFT)
        #rd = tkinter.Label( f023, text = " Qmin=0.0 Qmax=4.0")
        #rd.pack(padx=0,pady=0, side = tkinter.LEFT)
        #f023.pack(padx=0,pady=2, fill = tkinter.BOTH)
        self.dqs4 = self.frame.dsp_Si311
        self.dqs4.setMaximum(9.99)
        self.dqs4.setMinimum(0.01)
        self.dqs4.setSingleStep(0.01)
        self.dqs4.setValue(0.05)

        #f02.pack(padx=0, pady=2, side = tkinter.LEFT)
        #f0.pack(padx=5, pady=5)

        #f1 = tkinter.LabelFrame(self, text = 'Run No.')
        #rd = tkinter.Label(f1, text = "       ")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #self.run = tkinter.Spinbox( f1, from_=1000, to=50000, increment=1, width=5)
        #self.run.delete( 0, tkinter.END)
        #self.run.insert( 0, '2000')
        #self.run.pack(pady=2,side = tkinter.LEFT)
        self.run = self.frame.run
        self.run.setMaximum(100000)
        self.run.setMinimum(1000)
        self.run.setSingleStep(1)
        self.run.setValue(2000)
#T.Yamada start [20260130]
# Inside App.__init__
        self.cb_UseMon = self.frame.cb_UseMon
        self.mon_run = self.frame.mon_run
        # Disable the spinbox by default
        self.mon_run.setEnabled(False)
        # Connect toggle logic
        self.cb_UseMon.stateChanged.connect(self.toggle_mon_input)
        self.mon_run = self.frame.mon_run
        self.mon_run.setMaximum(100000)
        self.mon_run.setMinimum(1000)
        self.mon_run.setSingleStep(1)
        if FastChopperUse:
            self.mon_run.setValue(24939)#Monitor Stick 225Hz 3cm-3cm Att3
        else:
            self.mon_run.setValue(24487)#Monitor Stick for white. HV 1kV att0 Si111 LambdaCen 6p321 Kicker = 90000, timeout =
        #rd = tkinter.Label( f1, text = "    Temp. Sensor")
        #rd.pack(pady=0, side = tkinter.LEFT)
#.T.Yamada start
        ChList = ("A","B","C","C2","D","D2","D3","D4","D5","C_TC","D_TC","PEACE_U","PEACE_M","PEACE_L","PEACE_UB","PEACE_MB","PEACE_LB")
        #self.Ch = tkinter.StringVar()
        #self.Ch.set(ChList[6])
        #self.ChMenu = tkinter.OptiponMenu( f1, self.Ch, *ChList)
        #self.ChMenu.pack(pady=2, side = tkinter.LEFT)
        self.Ch = self.frame.Ch
#T.Yamada End
        #button2 = tkinter.Button( f1, text = "Read Temp.", command = self.readtemp)
        #button2.pack( side = tkinter.LEFT)
        self.frame.bt_ReadTemp.clicked.connect(self.readtemp)
        #f1.pack(padx=5, pady=5, fill = tkinter.BOTH)
        #f2 = tkinter.LabelFrame(self, text = 'Parameter')
        #f20 = tkinter.LabelFrame( f2, relief = tkinter.FLAT)
        #rd = tkinter.Label( f20, text="λcenter ")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #self.lam = tkinter.Spinbox( f20, from_=0, to=99.999, increment=0.001, width=6, format='%6.3f')
        #self.lam.delete( 0, tkinter.END)
        self.lam = self.frame.lam
        self.lam.setMaximum(99.999)
        self.lam.setMinimum(0.000)
        self.lam.setDecimals(3)
        self.lam.setSingleStep(0.001)
# 
        if ( FastChopperUse == True):
            #self.lam.insert( 0, ' 6.321')
            self.lam.setValue(6.321)
        else:
            #self.lam.insert( 0, ' 6.321')
            self.lam.setValue(6.321)

        #self.lam.pack(pady=0, side = tkinter.LEFT)
        #rd = tkinter.Label( f20, text="[A]/ dλ ")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #self.dl = tkinter.Spinbox( f20, from_=0, to=9.999, increment=0.001, width=5, format='%5.3f')
        #self.dl.delete( 0, tkinter.END)
        #self.dl.insert( 0, '4.15')
        #self.dl.pack(pady=0, side = tkinter.LEFT)
        self.dl = self.frame.dl
        self.dl.setMaximum(9.999)
        self.dl.setMinimum(0.000)
        self.dl.setDecimals(3)
        self.dl.setSingleStep(0.001)
        self.dl.setValue(4.15)

        #rd = tkinter.Label( f20, text="[A]")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #f20.pack(padx=5, pady=2, fill = tkinter.BOTH)

        #f21 = tkinter.LabelFrame( f2, relief = tkinter.FLAT)
        #rd = tkinter.Label( f21, text="Emin ")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #self.emin = tkinter.Spinbox( f21, from_=-99, to=999, increment=1, width=4, format='%3.0f')
        #self.emin.delete( 0, tkinter.END)
        self.emin = self.frame.emin
        self.emin.setMaximum(100000)
        self.emin.setMinimum(-100000)
        self.emin.setSingleStep(1)
# 
        if ( FastChopperUse == True):
            #self.emin.insert( 0, '-40')
            self.emin.setValue(-40)
        else:
            #self.emin.insert( 0, '-500')
            self.emin.setValue(-500)

        #self.emin.pack(pady=0, side = tkinter.LEFT)
        #rd = tkinter.Label( f21, text="μeV/ Emax ")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #self.emax = tkinter.Spinbox( f21, from_=0, to=999, increment=1, width=4, format='%3.0f')
        #self.emax.delete( 0, tkinter.END)
        self.emax = self.frame.emax
        self.emax.setMaximum(40000)
        self.emax.setMinimum(-40000)
        self.emax.setSingleStep(1)
# 
        if ( FastChopperUse == True):
            #self.emax.insert( 0, '100')
            self.emax.setValue(100)
        else:
            #self.emax.insert( 0, '1500')
            self.emax.setValue(1500)

        #self.emax.pack(pady=0, side = tkinter.LEFT)
        #rd = tkinter.Label( f21, text="μeV/ dE ")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #self.de = tkinter.Spinbox( f21, from_=0.01, to=99, increment=0.01, width=5, format='%5.2f')
        #self.de.delete( 0, tkinter.END)
        self.de = self.frame.de
        self.de.setMaximum(99.0)
        self.de.setMinimum(0.01)
        self.de.setSingleStep(0.01)
# 
        if ( FastChopperUse == True):
            #self.de.insert( 0, ' 0.50')
            self.de.setValue(0.50)
        else:
            #self.de.insert( 0, ' 2')
            self.de.setValue(2.0)

        #self.de.pack(pady=0, side = tkinter.LEFT)
        #rd = tkinter.Label(f21, text="μeV")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #f21.pack(padx=5, pady=2, fill = tkinter.BOTH)
#T. Yamada Add[20150601]
        #self.Ebin_flag = tkinter.BooleanVar()
        self.Ebin_flag = False
        #self.EbinFile_name = "not selected"
        
        #f3=tkinter.LabelFrame(self, text='Detector Efficiency Correction')
        #f21_1 = tkinter.LabelFrame(f2, relief = tkinter.FLAT)
        #cb = tkinter.Checkbutton(f21_1, text='User difined E Bin',variable = self.Ebin_flag).pack(padx=2, pady=2, side = tkinter.LEFT)
        #button5 = tkinter.Button(f21_1, text="Select file", command = self.loadEbinfile).pack(padx=2, pady=2, side = tkinter.LEFT)
        self.frame.cb_UserDefinedEBin.stateChanged.connect(self.changedUserDefinedEBin)
        self.frame.bt_UserDefinedEBin.clicked.connect(self.loadEbinfile)
        ##f21_2 = tkinter.Frame(f2,relief=tkinter.FLAT)
        #self.cb21_3 = tkinter.Label(f21_1, text = self.EbinFile_name)
        #self.cb21_3.pack(padx = 20, pady=2,side = tkinter.LEFT)
        ##f21_2.pack(padx=0, pady=2, fill = tkinter.BOTH)
        #f21_1.pack(padx=0, pady=2, fill = tkinter.BOTH)
        self.EbinFile_name = self.frame.txt_EbinFileName # "txt_EbinFileName" <- self.cb21_3  => self.EbinFile_name
#T. Yamada End [20150601]

        #f22 = tkinter.LabelFrame( f2, relief = tkinter.FLAT)
        #rd = tkinter.Label( f22, text = "T0Shift ")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #self.T0S = tkinter.Spinbox( f22, from_=0, to=99999, increment=1, width=5, format='%5.0f')
        #self.T0S.delete( 0, tkinter.END)
        self.T0S = self.frame.T0S
        self.T0S.setMaximum(99999)
        self.T0S.setMinimum(0)
        self.T0S.setSingleStep(1)
# 
        if ( FastChopperUse == True):
            #self.T0S.insert( 0, '12325')
            self.T0S.setValue(12325)
        else:
            #self.T0S.insert( 0, '120')
            self.T0S.setValue(120)

        #self.T0S.pack(pady=2, side = tkinter.LEFT)
        #rd = tkinter.Label( f22, text="[μs] ")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #f22.pack(padx=5, pady=2, fill = tkinter.BOTH)

        #f23 = tkinter.LabelFrame( f2, relief = tkinter.FLAT)
        #rd = tkinter.Label( f23, text = "StartTime")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #self.Sta = tkinter.Spinbox( f23, from_=0, to=9999999, increment=1, width=7, format='%7.0f')
        #self.Sta.pack(pady=0, side = tkinter.LEFT)
        self.Sta = self.frame.Sta
        self.Sta.setMaximum(9999999)
        self.Sta.setMinimum(0)
        self.Sta.setSingleStep(1)
        #rd = tkinter.Label( f23, text = "[sec.]/ EndTime ")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #self.End = tkinter.Spinbox( f23,from_=0,to=9999999,increment=1,width=7,format='%7.0f')
        #self.End.delete( 0, tkinter.END)
        #self.End.insert( 0, '9999999')
        #self.End.pack(pady=0, side = tkinter.LEFT)
        self.End = self.frame.End
        self.End.setMaximum(9999999)
        self.End.setMinimum(0)
        self.End.setSingleStep(1)
        self.End.setValue(1000000)
        #rd = tkinter.Label( f23, text = "[sec.]")
        #rd.pack(pady=0, side = tkinter.LEFT)
        #f23.pack(padx=5,pady=2, fill = tkinter.BOTH)
        #f2.pack(padx=5, pady=5, fill = tkinter.BOTH)

#T. Yamada Add[20140524]
        #self.DetEffCr_flag = tkinter.BooleanVar()
        #self.DetEffFile_name = "not selected"
        self.DetEffCr_flag = False
        self.DetEffFile_name = self.frame.txt_VanadiumCorr
        
        #f3=tkinter.LabelFrame(self, text='Detector Efficiency Correction')
        #f31 = tkinter.LabelFrame(f3, relief = tkinter.FLAT)
        #cb = tkinter.Checkbutton(f31, text='Vanadium Correction',variable = self.DetEffCr_flag).pack(padx=2, pady=2, side = tkinter.LEFT)
        #button4 = tkinter.Button(f31, text="Select file", command = self.loadfile).pack(padx=2, pady=2, side = tkinter.LEFT)
        self.frame.cb_VanadiumCorr.stateChanged.connect(self.changedVanadiumCorr)
        self.frame.bt_VanadiumCorr.clicked.connect(self.loadfile)
        #f31.pack(padx=0, pady=2, fill = tkinter.BOTH)
        ##f32 = tkinter.Frame(f3,relief=tkinter.FLAT)
        #self.cb31 = tkinter.Label(f31, text = self.DetEffFile_name)
        #self.cb31.pack(padx = 20, pady=2,side = tkinter.LEFT)
        ##f32.pack(padx=0, pady=2, side = tkinter.LEFT)
        #f3.pack(padx=5, pady=5, fill = tkinter.BOTH)
#T. Yamada End [20140524]
#T. Yamada Add [20141110]
        ##self.DoMask_flag = tkinter.BooleanVar()
        #self.MaskFile_name = "maskTY.txt"
        self.MaskFile_name = self.frame.txt_MaskFile
        
        #f4=tkinter.LabelFrame(self, text='Select mask file')
        #f41 = tkinter.LabelFrame(f4, relief = tkinter.FLAT)
        ##cb = tkinter.Checkbutton(f41, text='Vanadium Correction',variable = self.DetEffCr_flag).pack(padx=2, pady=2, side = tkinter.LEFT)
        #button4 = tkinter.Button(f41, text="Select file", command = self.loadMaskfile).pack(padx=2, pady=2, side = tkinter.LEFT)
        self.frame.bt_MaskFile.clicked.connect(self.loadMaskfile)
        #f41.pack(padx=0, pady=2, fill = tkinter.BOTH)
        #f42 = tkinter.Frame(f4,relief=tkinter.FLAT)
        #self.cb41 = tkinter.Label(f41, text = self.MaskFile_name)
        #self.cb41.pack(padx = 20, pady=2,side = tkinter.LEFT)
        #f41.pack(padx=0, pady=2, fill = tkinter.BOTH)
        ##f42.pack(padx=0, pady=2, side = tkinter.LEFT)
        #f4.pack(padx=5, pady=5, fill = tkinter.BOTH)
#T. Yamada End [20141110]

        #button1 = tkinter.Button(self, text = "Launch Data Reduction", command = self.launch)
        #button3 = tkinter.Button(self, text = "Quit", command = self.master.destroy)
        #button1.pack(side = tkinter.LEFT)
        #button3.pack(side = tkinter.RIGHT)
        #self.pack()
        self.frame.bt_LaunchDataRed.clicked.connect(self.launch)
        self.frame.bt_Quit.clicked.connect(self.close)
# self.step == 10: launch stand-by
        self.step = 11
        self.show()

    def toggle_mon_input(self, state):
        """Enable or disable the Monitor Run input based on checkbox state."""
        if self.cb_UseMon.isChecked():
            self.mon_run.setEnabled(True)
        else:
            self.mon_run.setEnabled(False)

    def changedUserDefinedEBin(self, evt=None):
        if self.frame.cb_UserDefinedEBin.checkState() == QtCore.Qt.Checked:
            self.Ebin_flag = True
        else:
            self.Ebin_flag = False
    def changedVanadiumCorr(self, evt=None):
        if self.frame.cb_VanadiumCorr.checkState() == QtCore.Qt.Checked:
            self.DetEffCr_flag = True
        else:
            self.DetEffCr_flag = False
    def loadfile(self):
        def _getcorrefftype(fname):
            f = open(fname,"r")
            line = f.readline()
            f.close()
            ret = 0
            if line.find(",") != -1:
                ret = len(line.split(",")) #ret = 120
            else:
                ret = len(line.split(" ")) #ret = 121
            
            if ret != 120 and ret !=121:
                print ("File is incorrect. Check the file {0}, {1}".format(fname, ret))

            return ret
        
        self.path_name = "/home/dnaadmin/ana/DNA"
        tmp_path = MU.UtsusemiEnvGetUserDir()
        if tmp_path != "":
            self.path_name = os.path.join(tmp_path, "ana", "DNA")
        #self.DetEffFile_name = tkFileDialog.askopenfilename(initialdir = self.path_name)
        tmp_filepath, filt = QtWidgets.QFileDialog.getOpenFileName(self, "Open File ...", self.path_name)
        if tmp_filepath == "":
            return
        else:
            self.DetEffFile_name.setText(tmp_filepath)
        #self.cb31.configure(text=self.DetEffFile_name)
        #self.DetEffFileType = _getcorrefftype(self.DetEffFile_name)
        self.DetEffFileType = _getcorrefftype(tmp_filepath)
        
        #print (self.DetEffFile_name, self.DetEffCr_flag.get(),self.DetEffFileType)
        print (tmp_filepath, self.DetEffCr_flag, self.DetEffFileType)
    

    def loadMaskfile(self):
        self.path_name = "/home/dnaadmin/ana/DNA/Mask"
        tmp_path = MU.UtsusemiEnvGetUserDir()
        if tmp_path != "":
            self.path_name = os.path.join(tmp_path, "ana", "DNA", "Mask")
        #self.MaskFile_name = tkFileDialog.askopenfilename(initialdir = self.path_name,filetypes=[('mask file','.txt')])
        tmp_filepath, filt = QtWidgets.QFileDialog.getOpenFileName(self, "Open Mask File ...", self.path_name, filter='Mask file (*.txt *.xml)')
        if tmp_filepath == "":
            return
        else:
            tmp_base_name = os.path.basename(tmp_filepath)
            self.MaskFile_name.setText(tmp_base_name)
        #self.MaskFile_name = os.path.basename(self.MaskFile_name)
        #self.cb41.configure(text=self.MaskFile_name)
        print (self.MaskFile_name.text())
       
    def loadEbinfile(self):
        self.path_name = "/home/dnaadmin/"
        tmp_path = MU.UtsusemiEnvGetUserDir()
        if tmp_path != "":
            self.path_name = tmp_path
        #self.EbinFile_name = tkFileDialog.askopenfilename(initialdir = self.path_name)
        tmp_filepath, filt = QtWidgets.QFileDialog.getOpenFileName(self, "Open Ebin File ...", self.path_name)
        #self.cb21_3.configure(text=self.EbinFile_name)
        if tmp_filepath == "":
            return
        else:
            self.EbinFile_name.setText(tmp_filepath)


    def sel_si(self):
        if self.step == 11:
            #self.si = self.v.get()
            self.si = self.rb_group.checkedId() - 1
            if self.si != 2:
                #self.MaskFile_name = "maskTY.txt"
                #self.cb41.configure(text=self.MaskFile_name)
                self.MaskFile_name.setText("maskTY.txt")
            elif self.si == 2:
                #self.MaskFile_name = "mask311.txt"
                #self.cb41.configure(text=self.MaskFile_name)
                self.MaskFile_name.setText("mask311.txt")

    def readtemp(self):
        if self.step == 11:
            #self.runNo = int(self.run.get())
            self.runNo = int(self.run.value())
            self.mon_runNo = int(self.mon_run.value())
            #TCh = self.Ch.get()
            TCh = self.Ch.currentText()
            print ("RunNo:{0:d}, TempCh: {1}".format(self.runNo,TCh))
            #get Run No.
            print ("SQWGUI--> Reading Temperature start")
            EC = Cmm.CheckSampleTempByRunNumber( self.runNo,TCh)
            print ("SQWGUI--> Reading Temperature end")
            MP.MPlot(EC)
            #self.errorstr.set("Temperature run# %d Ch %s" % (self.runNo, TCh))
            self.errorstr.setText("Temperature run# %d Ch %s" % (self.runNo, TCh))

    def launch(self):
        print ("koko283", self.step)
        if self.step == 11:
            self.mydatetime = datetime.datetime.now()
            datetimestr = self.mydatetime.strftime('%Y/%m/%d %H:%M:%S')
            datestr = self.mydatetime.strftime('Utsusemi%Y%m%d.txt')
            #Get Run No.
            #self.runNo = int(self.run.get())
            self.runNo = int(self.run.value())

            #Get Q parameter
            self.Qmin = 0.0
            if self.si == 0:#Si(111)
                #self.DQ = float(self.dqs1.get())
                self.DQ = float(self.dqs1.value())
                self.Qmax = 2.0
            elif self.si == 1:#Si(333)
                #self.DQ = float(self.dqs3.get())
                self.DQ = float(self.dqs3.value())
                self.Qmax = 6.0
            elif self.si == 2:
                #self.DQ = float(self.dqs4.get())
                self.DQ = float(self.dqs4.value())
                self.Qmax = 4.0
            
            QParam = "%.1f,%.3f,%.3f" %(self.Qmin,self.Qmax,self.DQ)	
            print ("->>QParam: {0}".format(QParam))

            #Get Lambda Parameter
            # LambdaCenter = float(self.lam.get())
            # dLambda = float(self.dl.get())
            #self.LambdaParam = "%.4f,%.4f" %(float(self.lam.get()),float(self.dl.get()))
            self.LambdaParam = "%.4f,%.4f" %(float(self.lam.value()),float(self.dl.value()))
            print ("->>LambdaParam: {0}".format(self.LambdaParam))

            #Get HWParam
            # Emin = float(self.emin.get())/1000.0
            # Emax = float(self.emax.get())/1000.0
            # dE = float(self.de.get())/1000.0
            #self.HWParam = "%.5f,%.5f,%.5f" %((float(self.de.get())/1000.0),(float(self.emin.get())/1000.0),(float(self.emax.get())/1000.0))
            self.HWParam = "%.5f,%.5f,%.5f" %((float(self.de.value())/1000.0),(float(self.emin.value())/1000.0),(float(self.emax.value())/1000.0))
            print ("->>HWParam: {0}".format(self.HWParam))

            #Get T0Shift
            #self.T0Shift = float(self.T0S.get())
            self.T0Shift = float(self.T0S.value())
            print ("->>T0Shift: {0}".format( self.T0Shift))

            #Get Time Parameter
            # startTime = int(self.Sta.get())
            # endTime = int(self.End.get())
            #self.TimeParam = "%d,%d" %(int(self.Sta.get()), int(self.End.get()))
            self.TimeParam = "%d,%d" %(int(self.Sta.value()), int(self.End.value()))
            print ("->>TimeParam: {0}".format(self.TimeParam))

            #Write log file
            self.fp = open( "%s" % (datestr), "a")
            self.fp.write( "%s run:%d Si" % (datetimestr, self.runNo))
            if self.si == 0:
                #self.fp.write( "(111):de:%s min:%3.1f max:%3.1f" % (self.dqs1.get(),0,2.0))
                self.fp.write( "(111):de:%s min:%3.1f max:%3.1f" % (self.dqs1.value(),0,2.0))
            elif self.si == 1:
                #self.fp.write( "(333):de:%s min:%3.1f max:%3.1f" % (self.dqs3.get(),0,6.0))
                self.fp.write( "(333):de:%s min:%3.1f max:%3.1f" % (self.dqs3.value(),0,6.0))
            elif self.si == 2:
                #self.fp.write( "(311):de:%s min:%3.1f max:%3.1f" % (self.dqs4.get(),0,6.0))
                self.fp.write( "(311):de:%s min:%3.1f max:%3.1f" % (self.dqs4.value(),0,6.0))
            #self.fp.write(" lambda:%s dlambda:%s" % (self.lam.get(), self.dl.get()))
            self.fp.write(" lambda:%6.3f dlambda:%5.3f" % (self.lam.value(), self.dl.value()))
            #self.fp.write(" emin:%s emax:%s de:%s" % (self.emin.get(), self.emax.get(),self.de.get()))
            self.fp.write(" emin:%3.0f emax:%3.0f de:%5.2f" % (self.emin.value(), self.emax.value(),self.de.value()))
            #self.fp.write(" T0shift:%s" % (self.T0S.get()))
            self.fp.write(" T0shift:%5.0f" % (self.T0S.value()))
            #self.fp.write(" Start:%s End:%s" % (self.Sta.get(), self.End.get()))
            self.fp.write(" Start:%7.0f End:%7.0f" % (self.Sta.value(), self.End.value()))
            #self.fp.write(" Maskfile:%s" % (self.MaskFile_name))
            self.fp.write(" Maskfile:%s" % (self.MaskFile_name.text()))
            #self.fp.write(" EfficiencyFile:%s %s\n" % ( self.DetEffFile_name, self.DetEffCr_flag.get()))
            if self.DetEffCr_flag:
                self.fp.write(" EfficiencyFile:%s True\n" % ( self.DetEffFile_name.text()))
            else:
                self.fp.write(" EfficiencyFile:%s False\n" % ( self.DetEffFile_name.text()))
            self.fp.close()

            self.step = 0
            #self.errorstr.set("Check Data  (0/11)")
            self.errorstr.setText("Check Data  (0/11)")
            #self.after( 100, self.countup)
            self.timer = QtCore.QTimer(self)
            self.timer.timeout.connect(self.countup)
            self.timer.start(100)

    def countup(self):
        print ("TY1", self.step)
        if self.step == 0:
            copyresult, messg = CopyEventData(int(self.runNo))
            #self.errorstr.set(messg)
            self.errorstr.setText(messg)
            if copyresult == 1:
                self.step = 10
                print ("TY2", copyresult, messg, self.step)
            else:
                #self.errorstr.set("GetMonHistogram.  (1/11)")
                print ("TY3", copyresult, messg, self.step)
                self.errorstr.setText("GetMonHistogram.  (1/11)")
                print ("TY3_1",self.runNo, self.LambdaParam, self.T0Shift, 0.0,  self.TimeParam, FastChopperUse)  
                if self.cb_UseMon.isChecked():#20260130 Yamada add
                    print("Using Monitor Stick")
                    self.mon_runNo = int(self.mon_run.value())
                    self.EC = Cmm.GetHistogramMonAtSmp(self.mon_runNo, True, self.LambdaParam, self.T0Shift, 0.0, False, "0/1000000", FastChopperUse,False)  
#                    self.EC = Cmm.GetHistogramMon(self.mon_runNo, True, self.LambdaParam, self.T0Shift, 0.0, False, self.TimeParam, FastChopperUse)  
                else:
                    self.EC = Cmm.GetHistogramMon(self.runNo, True, self.LambdaParam, self.T0Shift, 0.0, False, self.TimeParam, FastChopperUse)  
                    Cmm.MutiplyConstant(self.EC, 1e-09)
                Cmm.OutputECText( self.EC, "TY")
                #self.errorstr.set("MultiplyConstant. (2/11)")
                self.errorstr.setText("MultiplyConstant. (2/11)")
                self.step = 1
        elif self.step == 1:
            if self.si == 0:
                #self.errorstr.set("GetHistogramHW.   (3/11)")
                self.errorstr.setText("GetHistogramHW.   (3/11)")
            elif self.si == 1:
                #self.errorstr.set("GetHistogramHW333.(3/11)")
                self.errorstr.setText("GetHistogramHW333.(3/11)")
            elif self.si == 2:
                #self.errorstr.set("GetHistogramHW311.(3/11)")
                self.errorstr.setText("GetHistogramHW311.(3/11)")
            self.step = 2
        
        elif self.step == 2:
            #if self.Ebin_flag.get():
            if self.Ebin_flag:
                self.HWParam = MDCR._readBinInfo(self.EbinFile_name.text(),"\n",",")
                #print "koko", self.HWParam
                #print "kokoko"
                #return -1

            if self.si == 0:
                self.DAT = Cmm.GetHistogramHW( self.runNo, self.HWParam, self.LambdaParam, self.T0Shift, False, self.TimeParam, FastChopperUse)
            elif self.si == 1:
                self.DAT = Cmm.GetHistogramHW333( self.runNo, self.HWParam, self.LambdaParam, self.T0Shift, False, self.TimeParam, FastChopperUse)
            elif self.si == 2:
                self.DAT = Cmm.GetHistogramHW311( self.runNo, self.HWParam, self.LambdaParam, self.T0Shift, False, self.TimeParam, FastChopperUse)
            #self.errorstr.set("DoMask.           (4/11)")
            self.errorstr.setText("DoMask.           (4/11)")
            if self.cb_UseMon.isChecked(): #20260130 Yamada Add
                factorBC = 1e8
                Cmm.NormByBeamCurrent(self.DAT,factorBC,0.0,True)
            self.step = 3
        elif self.step == 3:
            """
            [20141110 Yamada Modified]
            if self.si != 2:
                Cmm.DoMask(self.DAT, "maskTY.txt")
            else:
                Cmm.DoMask(self.DAT, "mask311.txt")
            """
            Cmm.DoMask(self.DAT, self.MaskFile_name.text())
            #self.errorstr.set("ILambdaCorrDNA.   (5/11)")
            self.errorstr.setText("ILambdaCorrDNA.   (5/11)")
            self.step = 4
        elif self.step == 4:
            if self.cb_UseMon.isChecked(): #20260130 Yamada Add
                if FastChopperUse:
                    AttUse = True
                    monDatFile = "monitor_data_stick_highreso.dat"
                else:
                    AttUse = False
                    monDatFile = "monitor_data_stick_highflux.dat"
                self.ECM = Cmm.ILambdaCorrUseMonAtSmpDNA(dat=self.DAT,ec=self.EC,monDatFile=monDatFile,isHighReso=AttUse,attenuateVal=0.0) #isHighReso=True means using Att, False means not using Att. If other attenuator is used for monitor stick, attenuateVal should be changed. The default (0.0) is calculated by Dr. Matsuura.
                print("Using Monitor Stick")
            else:
                self.ECM = Cmm.ILambdaCorrDNA( self.DAT, self.EC, True)
            #self.errorstr.set("SolidAngleCorrDNA.(6/11)")
            self.errorstr.setText("SolidAngleCorrDNA.(6/11)")
            self.step = 5
        elif self.step == 5:
            #if self.DetEffCr_flag.get() and self.DetEffFileType == 120:
            if self.DetEffCr_flag and self.DetEffFileType == 120:
                self.ECM2 = Cmm.SolidAngleCorrDNA( self.ECM, True, False, False, "sample", DetEffDataPath=self.DetEffFile_name.text() )
                self.ECM2 = EneOrig.DoEfficiencyCorrection(dat=self.ECM2,filename=self.DetEffFile_name.text(),mode=0)
            else:
                self.ECM2 = Cmm.SolidAngleCorrDNA( self.ECM, True, False, self.DetEffCr_flag, "sample", DetEffDataPath=self.DetEffFile_name.text() )
            #self.errorstr.set("MultiplyConstant. (7/11)")
            self.errorstr.setText("MultiplyConstant. (7/11)")
            self.step = 6
        elif self.step == 6:
            if self.cb_UseMon.isChecked(): #20260130 Yamada Add
                if FastChopperUse:
                    Cmm.MutiplyConstant(self.ECM2, 1e1)
                else:
                    Cmm.MutiplyConstant(self.ECM2, 1e2)
            else:
                Cmm.MutiplyConstant( self.ECM2, 1e-06)
            #self.errorstr.set("CreateQEMap.      (8/11)")
            self.errorstr.setText("CreateQEMap.      (8/11)")
            self.step = 7
        elif self.step == 7:
            Cmm.KiKfCorrection(self.ECM2)
            #self.errorstr.set("KiKfCorrection.      (9/11)")
            self.errorstr.setText("KiKfCorrection.      (9/11)")
            self.step = 8
        elif self.step == 8:
            self.ECA = Cmm.CreateQEMap( self.ECM2, self.Qmin, self.Qmax, self.DQ)
            #self.errorstr.set("OutoutECA.        (10/11)")
            self.errorstr.setText("OutoutECA.        (10/11)")
            self.step = 9
        elif self.step == 9:
            footer = "_GUIQE"
            if self.DetEffCr_flag:
                footer = "_VGUIQE"
            Cmm.OutputECA( self.ECA, footer)
            Cmm.OutputECAText( self.ECA, footer)
            Cmm.OutputECADAVEText( self.ECA, footer)
            #T.Yamada Add[20150601]
            #if self.Ebin_flag.get():
            if self.Ebin_flag:
                Cmm.OutputNeiECAText(self.ECA,"_neimMDRQE")
            #T.Yamada End[20150601]
            
            #self.errorstr.set("M2PLOT(ECA)      (11/11)")
            self.errorstr.setText("M2PLOT(ECA)      (11/11)")
            self.step = 10
        elif self.step == 10:
            MP2.M2PlotPlusCui(self.ECA).ShowData()
            #self.errorstr.set("M2PLOT end. run# %d" % (self.runNo))
            self.errorstr.setText("M2PLOT end. run# %d" % (self.runNo))
            self.step = 11
        #if self.step < 11:
        #    self.after(200, self.countup)
        if self.step == 11:
            self.timer.stop()

def CopyEventData(RunNo):
    #if RunNo < 14082:
    if RunNo < 0:
        command = "ssh dnaadmin@192.168.1.10 /home/dnaadmin/Yamada/01_CopyEventData/CopyEventEdata.sh %d" %(RunNo)
        args = command.split(" ")
        proc = subprocess.Popen(args, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
        stdout_data, stderr_data = proc.communicate()
        print ("stdout_data >> {0}".format(stdout_data.decode('utf-8')))
        print ("stderr_data >> {0}".format(stderr_data.decode('utf-8').replace("\n","")))
        result = proc.returncode
        #proc.close()
        if result == 1:
            messg =  "DNA%06d_* is not found on /data and /ifs_data/DNA/DNA" %RunNo
        else:
            messg =  "DNA%06d_* is ready for the reduction." %RunNo
    else:
        result = 0
        messg =  "DNA%06d_* is ready for the reduction." %RunNo

    return result, messg

if __name__ == "__main__":

    if ( os.environ.get("FastChopperUse")=="True"):
        FastChopperUse = True
    else:
        FastChopperUse = False
    if PYSIDEVER == 2:
        if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
            QtWidgets.QApplication.setAttribute(
                QtCore.Qt.AA_EnableHighDpiScaling, True)

    #app = App()
    #app.mainloop()
    app = QApplication(sys.argv)
    win = App(None)
    if PYSIDEVER == 6:
        sys.exit(app.exec())
    else:
        sys.exit(app.exec_())
