#! /usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
import time
import os
import sys
import shutil
import Manyo as mm
import Manyo.Utsusemi as mu
import Cmm
import uGao.MPlot as MP
import uGao.M2PlotPlusCui as MP2
import ElasticScanGUIBase as ESB
import T0fileMake as T0M
import subprocess

import ElasticScanPy3 as ESP3

PYSIDEVER = 6
try:
    from PySide6 import QtCore, QtGui, QtWidgets
    from PySide6.QtWidgets import QApplication, QFileDialog, QListWidgetItem, QMessageBox
    from PySide6.QtCore import QFile
    from ui6_ElasticScanGUIQt 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_ElasticScanGUIQt 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)

        bkg = self.findChild(QtWidgets.QWidget, 'background')
        bkg.setStyleSheet("background-color: cyan")

        self.run = self.findChild(QtWidgets.QSpinBox, 'run')
        self.readtemp_bt = self.findChild(QtWidgets.QPushButton, 'readtemp_bt')
        self.Sta = self.findChild(QtWidgets.QDoubleSpinBox, 'Sta')
        self.End = self.findChild(QtWidgets.QDoubleSpinBox, 'End')
        self.End_2 = self.findChild(QtWidgets.QDoubleSpinBox, 'End_2')
        self.Bin = self.findChild(QtWidgets.QDoubleSpinBox, 'Bin')
        self.Ti = self.findChild(QtWidgets.QDoubleSpinBox, 'Ti')
        self.Tf = self.findChild(QtWidgets.QDoubleSpinBox, 'Tf')
        self.TBin = self.findChild(QtWidgets.QDoubleSpinBox, 'TBin')
        self.rb1_NFinished = self.findChild(QtWidgets.QRadioButton, 'rb1_NFinished')
        self.rb1_Finished = self.findChild(QtWidgets.QRadioButton, 'rb1_Finished')
        self.rb2_FCOFF = self.findChild(QtWidgets.QRadioButton, 'rb2_FCOFF')
        self.rb2_FCON_11_225 = self.findChild(QtWidgets.QRadioButton, 'rb2_FCON_11_225')
        self.rb2_FCON_33_225 = self.findChild(QtWidgets.QRadioButton, 'rb2_FCON_33_225')
        self.rb2_FCON_1S_225 = self.findChild(QtWidgets.QRadioButton, 'rb2_FCON_1S_225')
        self.rb2_FCON_33_300 = self.findChild(QtWidgets.QRadioButton, 'rb2_FCON_33_300')
        self.rb2_FCON_11_300 = self.findChild(QtWidgets.QRadioButton, 'rb2_FCON_11_300')
        self.T0shift = self.findChild(QtWidgets.QSpinBox, 'T0shift')
        self.dqs1 = self.findChild(QtWidgets.QDoubleSpinBox, 'dqs1')
        self.emin = self.findChild(QtWidgets.QDoubleSpinBox, 'emin')
        self.emax = self.findChild(QtWidgets.QDoubleSpinBox, 'emax')
        self.de = self.findChild(QtWidgets.QDoubleSpinBox, 'de')
        self.rb3_CHOFF = self.findChild(QtWidgets.QRadioButton, 'rb3_CHOFF')
        self.rb3_CHON_11_225 = self.findChild(QtWidgets.QRadioButton, 'rb3_CHON_11_225')
        self.dqs3 = self.findChild(QtWidgets.QDoubleSpinBox, 'dqs3')
        self.emin3 = self.findChild(QtWidgets.QDoubleSpinBox, 'emin3')
        self.emax3 = self.findChild(QtWidgets.QDoubleSpinBox, 'emax3')
        self.de3 = self.findChild(QtWidgets.QDoubleSpinBox, 'de3')
        self.button1 = self.findChild(QtWidgets.QPushButton, 'button1')
        self.button3 = self.findChild(QtWidgets.QPushButton, 'button3')
        
        #Tkinter.Frame.__init__(self, master,bg="#00FFFF")
        #self.master.title("DNA Elastic Scan Reduction Check")

        #self.errorstr
# Set Run No.
        #self.run.insert( 0, '10371')
        self.run.setValue(10371)
        
        # Read Temperature
        ChList = ("A","B","C","C2","D","D2","D3","D4","D5","PEACE_U","PEACE_M","PEACE_L","PEACE_UB","PEACE_MB","PEACE_LB")
        #self.ChMenu
        self.ChMenu = self.findChild(QtWidgets.QComboBox, 'ChMenu')
        self.readtemp_bt.clicked.connect(self.readtemp)

        #####################
        #Set Time Parameter
        #self.Sta
        #self.End
        #self.Bin
        ###########
        #Set Tempaerature Parameter
        #self.Ti
        #self.Tf.insert( 0, '300')
        self.Tf.setValue(300)
        #self.TBin.insert( 0, '1')
        self.TBin.setValue(1)

        self.rb1_grp = QtWidgets.QButtonGroup()
        self.rb1_grp.addButton(self.rb1_NFinished, 1)
        self.rb1_grp.addButton(self.rb1_Finished, 2)
        self.rb1_grp.button(1).setChecked(True)
        

# Si(111) self.si < 4, Si(333) self.si > 3
# Si111 Select
        self.si = 0

        self.rb2_FCOFF.clicked.connect(self.sel_si111)
        self.rb2_FCON_11_225.clicked.connect(self.sel_si111)
        self.rb2_FCON_33_225.clicked.connect(self.sel_si111)
        self.rb2_FCON_1S_225.clicked.connect(self.sel_si111)
        self.rb2_FCON_33_300.clicked.connect(self.sel_si111)
        self.rb2_FCON_11_300.clicked.connect(self.sel_si111)
        self.v111 = QtWidgets.QButtonGroup()
        self.v111.addButton(self.rb2_FCOFF, 1)
        self.v111.addButton(self.rb2_FCON_11_225, 2)
        self.v111.addButton(self.rb2_FCON_33_225, 3)
        self.v111.addButton(self.rb2_FCON_1S_225, 4)
        self.v111.addButton(self.rb2_FCON_33_300, 5)
        self.v111.addButton(self.rb2_FCON_11_300, 6)

        self.rb3_CHOFF.clicked.connect(self.sel_si333)
        self.rb3_CHON_11_225.clicked.connect(self.sel_si333)
        #self.v333 = QtWidgets.QButtonGroup()
        #self.v333.addButton(self.rb3_CHOFF, 5)
        #self.v333.addButton(self.rb3_CHON_11_225, 6)
        self.v111.addButton(self.rb3_CHOFF, 7)
        self.v111.addButton(self.rb3_CHON_11_225, 8)
        
        self.dqs1.setValue(0.05)

        #self.v111.set(2)
        self.v111.button(3).setChecked(True)

        self.emin.setValue(-4)
        self.emax.setValue(4)
        self.de.setValue(2)
	
        #[20220403] T0shift Add. by TY 
        self.T0shift.setValue(12325)
        #self.label_22.setText()

#Si 333 GUI
        self.dqs3.setValue(0.15)
        #self.v333.set(0)
        #if self.v333.checkedButton() is not None:
        #    self.v333.checkedButton().setChecked(False)
        ##self.v333.button(1).setChecked(True)
        
        self.emin3.setValue(-500)
        self.emax3.setValue(100)
        self.de3.setValue(50)
        #rd = Tkinter.Label( f33, text="μeV")

        self.show()

# Button
        #button1 = Tkinter.Button(self, text = "Reduction Start", command = self.launch)
        #button3 = Tkinter.Button(self, text = "Quit", command = self.master.destroy)
        self.button1.clicked.connect(self.launch)
        self.button3.clicked.connect(self.closeThis)

# self.step == 10: launch stand-by
        self.step = 10

        self.FastChopperUse = True
        self.CommentHeader = "ElasticGUI ->>"

    def sel_si111(self):
        if self.step == 10:
            #i = self.v111.get()
            i = self.v111.checkedId() - 1
        if ( self.si != i):
            #self.v333.set(0)
            #if self.v333.checkedButton() is not None:
            #    self.v333.checkedButton().setChecked(False)
            self.si = i
            self.emin.setValue(0.0)
            self.emax.setValue(0.0)
            self.de.setValue(0.0)
        if ( i == 0):
            self.emin.setValue(-200)
            self.emax.setValue(50)
            self.de.setValue(50)
            self.FastChopperUse = False
            self.T0shift.setValue(120)
        elif ( i == 1):
            self.emin.setValue(-7)
            self.emax.setValue(5)
            self.de.setValue(3)
            self.FastChopperUse = True
            self.T0shift.setValue(12325)
        elif ( i == 2):
            self.emin.setValue(-4)
            self.emax.setValue(4)
            self.de.setValue(2)
            self.FastChopperUse = True
            self.T0shift.setValue(12325)
        elif ( i == 4):
            self.emin.setValue(-2)
            self.emax.setValue(2)
            self.de.setValue(2)
            self.FastChopperUse = True
            self.T0shift.setValue(12325)
        elif ( i == 5):
            self.emin.setValue(-2)
            self.emax.setValue(2)
            self.de.setValue(2)
            self.FastChopperUse = True
            self.T0shift.setValue(12275)
        else:
            self.emin.setValue(-10)
            self.emax.setValue(10)
            self.de.setValue(5)
            self.FastChopperUse = True
            self.T0shift.setValue(12325)

    def sel_si333(self):
        if self.step == 10:
            #i = self.v333.get()
            #i = self.v333.checkedId() - 1
            i = self.v111.checkedId() - 1
            if ( self.si != i):
                #self.v111.set(-1)
                #if self.v111.checkedButton() is not None:
                #    print("#[inamura 230301] setChecked(False) checked ID={}".format(self.v111.checkedId()))
                #    self.v111.button(2).setChecked(True)
                #    #self.v111.checkedButton().setChecked(False)
                self.si = i
                self.emin3.setValue(0)
                self.emax3.setValue(100)
                self.de3.setValue(50)
            if ( i == 6):
                self.emin3.setValue(-500)
                self.FastChopperUse = False
            else:
                self.emin3.setValue(-100)
                self.FastChopperUse = True

    def readtemp(self):
        if self.step == 10:
            #runNo = int(self.run.get())
            #TCh = self.Ch.get()
            runNo = int(self.run.value())
            TCh = self.ChMenu.currentText()
            #TCh = self.ChMenu.get()
            print (self.CommentHeader, "RunNo: DNA%6d" %(runNo))
            print (self.CommentHeader, "Temperature Sensor: %s" %(TCh))
            print (self.CommentHeader, "Reading Temperature Start....")
            EC = Cmm.CheckSampleTempByRunNumber( runNo,TCh)
            print (self.CommentHeader, "Reading Temperature end")
            MP.MPlot(EC)
            self.frame.errorstr.setText("Temperature run# %d Ch %s" % (runNo, TCh))

    def closeThis(self):
        self.close()

    def launch(self):
        self.SetParams()
        self.StartElasticScan() #temporal comment out

    def SetParams(self):
        #self.RunNo = int(self.run.get())
        #self.Tch = self.Ch.get()
        self.RunNo = self.run.value()
        self.Tch = self.ChMenu.currentText()
        print (self.CommentHeader, "Run No.:", self.RunNo )
        print (self.CommentHeader, "Temperature Sensor: %s" %(self.Tch))
        #self.StartTime = self.Sta.get()
        #self.EndTime = self.End.get()
        #self.TimeBin = self.Bin.get()
        self.StartTime = str(self.Sta.value())
        self.EndTime = str(self.End.value())
        self.TimeBin = str(self.Bin.value())
        print (self.CommentHeader, "StartTime: %s sec" %(self.StartTime))
        print (self.CommentHeader, "EndTime: %s sec" %(self.EndTime))
        print (self.CommentHeader, "TimeBin: %s sec" %(self.TimeBin))
        print (self.CommentHeader, "FastChopperUse:", self.FastChopperUse)
        #self.StartTemp = self.Ti.get()
        #self.EndTemp = self.Tf.get()
        #self.TempBin = self.TBin.get()
        self.StartTemp = str(self.Ti.value())
        self.EndTemp = str(self.Tf.value())
        self.TempBin = str(self.TBin.value())
        print (self.CommentHeader, "Start Temperature: %s K" %(self.StartTemp))
        print (self.CommentHeader, "End Temperature: %s K" %(self.EndTemp))
        print (self.CommentHeader, "Temperature BIn: %s K" %(self.TempBin))


        self.Analyzer = 111
        self.Emin = 0
        self.Emax = 0
        self.Ebin = 0
        self.Qmin = 0
        self.Qmax = 0
        self.Qbin = 0
        
        #Mode = self.v111.get()
        #Mode3 = self.v333.get()
        Mode = self.v111.checkedId() - 1
        Mode3 = self.v111.checkedId() - 3
        if Mode3 ==4 or Mode3 ==5:
            self.Analyzer = 333
        print (self.CommentHeader, "Analyzer:%d" %(self.Analyzer))
        
        if Mode <=5 and Mode>=0:
            self.Emin = self.emin.value()
            self.Emax = self.emax.value()
            self.Ebin = self.de.value()
            self.Qmax = 2.0
            self.Qbin = str(self.dqs1.value())
        elif Mode3 >=4:
            self.Emin = self.emin3.value()
            self.Emax = self.emax3.value() 
            self.Ebin = self.de3.value()
            self.Qmax = 6.0
            self.Qbin = str(self.dqs3.value())
        else:
            print (self.CommentHeader, "EBin Set Error")
            return -1
        
        self.Emin = float(self.Emin)/1000
        self.Emax = float(self.Emax)/1000
        self.Ebin = float(self.Ebin)/1000
        print (self.CommentHeader, "Emin:%.4f" %(self.Emin))
        print (self.CommentHeader, "Emax:%.4f" %(self.Emax))
        print (self.CommentHeader, "Ebin:%.6f" %(self.Ebin))
        print (self.CommentHeader, "Qmin:%2.1f" %(self.Qmin))
        print (self.CommentHeader, "Qmax:%2.1f" %(self.Qmax))
        print (self.CommentHeader, "Qbin:%s" %(self.Qbin))

    def showplot(self,dat):
        if type(dat) == type(mm.ElementContainer()):
            MP.MPlot(dat)
        elif type(dat) == type(mm.ElementCotainerArray()):
            MP2.M2Plot(dat)
        else:
            print (self.CommentHeader, "dat is not ElementContainer or ElementContainerArray")
            print (self.CommentHeader, "dat type is ", type(dat))

    def StartElasticScan(self):
        print (self.CommentHeader)
        print (self.CommentHeader, "ElasticScan Reduction Start")
        
        inifile = "ESGUIParams.ini"
        iniparams = ESB.SetESiniFile(inifile)
        
        iniparams.setparams("laticetype",self.Analyzer)
        if self.FastChopperUse:
            iniparams.setparams("UseFastChopper","True")
            if self.Analyzer == 111:
#                Mode = self.v111.get()
                #iniparams.setparams("t0_offset",self.T0shift.get())
                iniparams.setparams("t0_offset",str(self.T0shift.value()))
#                print (Mode)
#                if(Mode == 4):
#                    iniparams.setparams("t0_offset","12375")
#                elif(Mode == 5):
#                    iniparams.setparams("t0_offset","12275")
#                    #iniparams.setparams("t0_offset","12365")
#                else:
#                    iniparams.setparams("t0_offset","12325")
            elif self.Analyzer == 333:
                iniparams.setparams("t0_offset","4091")
        else:
            iniparams.setparams("UseFastChopper","False")
            #iniparams.setparams("t0_offset",self.T0shift.get())
            iniparams.setparams("t0_offset",str(self.T0shift.value()))
            #iniparams.setparams("t0_offset","120")
        
        iniparams.writeESinifiles()
        #---LambdaParam
        LambdaCenter = 6.321
        dLambda = 4.15 
        if self.Analyzer == 333:
            LambdaCenter = 3.4 
            dLambda = 4.16 
        
        LambdaParam = "%.4f,%.4f" %(LambdaCenter,dLambda)
        HWParam ="%.4f,%4f,%.6f" %(self.Ebin,self.Emin,self.Emax)
        HWParam2 ="%.4f,%4f" %(self.Emin,self.Emax)
        QParam = "%.2f,%.2f,%s" %(self.Qmin,self.Qmax,self.Qbin)
        print (self.CommentHeader, "HWParam: %s" %( HWParam))
        print (self.CommentHeader, "HWParam2: %s" %(HWParam2))
        print (self.CommentHeader, "LambdaParam: %s"  %(LambdaParam))
        print (self.CommentHeader, "Qparam: %s" %(QParam))
       
        TimeParam = "%s,%s,%s" %(self.StartTime,self.EndTime,self.TimeBin)
        TempParam = "%s,%s,%s" %(self.StartTemp,self.EndTemp,self.TempBin)
        print (self.CommentHeader, "TimeParam: %s" %(TimeParam))
        print (self.CommentHeader, "TempCh: %s" %(self.Tch))
        print (self.CommentHeader, "TempParam: %s" %(TempParam))

        dataPath = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp")  #[inamura 230301]
        #dataPath = "/home/dnaadmin/DNA/tmp/" #T.Yamada[130218]
        ECMbstName = "ECM_%d_ES.bst" %(self.RunNo)
        
        FileHeader = "ESGUIRun"
        ESName = "%s%dES.txt" % (FileHeader, self.RunNo)
        ESTimeName = "%s%dU2time.txt" % (FileHeader, self.RunNo)
        ESTempName = "%s%dU2vsT.txt" % (FileHeader, self.RunNo)
        TIName = "%s%dTI.txt" % (FileHeader, self.RunNo)
        TITimeName = "%s%dTItime.txt" % (FileHeader, self.RunNo)
        TITempName = "%s%dTIvsT.txt" % (FileHeader, self.RunNo)
        TempLogName = "%s%dTempLog.txt" %(FileHeader, self.RunNo)
    
        #copyresult, messg =CopyEventData(int(self.RunNo))
        #print (messg) 

        #print (type(self.RunNo), self.RunNo)
        T0M.MakeT0file(str("%06d" %int(self.RunNo)))

        import ElasticScan 
        #Make Case Info xml
        casefname = ESP3.MakeCaseInfoXML(float(self.StartTime), float(self.EndTime), float(self.TimeBin))
        print (self.CommentHeader, "ECM make start")
        ECM = ESP3.ESTimeSlice(RunNo=int(self.RunNo), dataFolder="/data", HWParam=HWParam, LambdaParam=LambdaParam, QParam=QParam, inifile=inifile, cfile=casefname)
        #ECM = ElasticScan.GetQETimeECMMulth(self.RunNo, HWParam, LambdaParam, QParam, TimeParam, inifile)
        print (self.CommentHeader, "ECM make end")
        
        #ECM = ElasticScan.ReadECM(ECMbstName)
        EC = ElasticScan.ElasticScanTotalIntensity(ECM, HWParam2, QParam, inifile)
        print (self.CommentHeader, "Total Intensity vs Time")
        ElasticScan.OutputECText(EC, TITimeName)
        ElasticScan.OutPutElasticScanECM(ECM)
        #del ECM
        #del ElasticScan
        self.showplot(EC)
        print ("Finished")
        EC2 = Cmm.CheckSampleTempByRunNumber(self.RunNo,self.Tch)
        EC4 = ESP3.ConvertXaxisFromTimeToTemp(EC,EC2)
        ElasticScan.OutputECText(EC4, TITempName) #TotalIntensity vs T
        self.showplot(EC4)
        #u2 vs time is calculated
        ECA = ElasticScan.ElasticScanQ2LnI(ECM, HWParam2, QParam, inifile)
        EC1 = ElasticScan.ElasticScanFit(ECA, "p1")
        ElasticScan.OutputECText(EC1, ESTimeName) # U2 vs Time
        self.showplot(EC1)
        EC3 = ESP3.ConvertXaxisFromTimeToTemp(EC1,EC2)
        ElasticScan.OutputECText(EC3, ESTempName) #U2 vs T
        self.showplot(EC3)
        del ECM
        del ElasticScan
        del ECA
        print (self.CommentHeader, "ElasticScan Reduction End")
        print (self.CommentHeader, "I(Q) vs time is saved as \n%sRun%sIQ.txt\n" %(dataPath,self.RunNo) )
        print (self.CommentHeader, "u2 is saved as \n%s%s\n%s%s\n" %(dataPath, ESTempName, dataPath, ESTimeName))
        print (self.CommentHeader, "Total intensity is saved as \n%s%s\n%s%s\n" %(dataPath, TITempName, dataPath, TITimeName))
        #print (self.CommentHeader, "Temperature Log is saved as \n%s%s\n" %(dataPath, TempLogName))
        return -1
        

def CopyEventData(RunNo):
    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 >>", stdout_data)
    print ("stderr_data >>", stderr_data.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
    return result, messg


if __name__ == "__main__":
    FastChopperUse = False
    if PYSIDEVER == 2:
        if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
            QtWidgets.QApplication.setAttribute(
                QtCore.Qt.AA_EnableHighDpiScaling, True)

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