#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 09:44:07 2019
Window for Measurement
@author: juliengautier
modified 2019/08/13 : add motors RSAI position and zoom windows
modified 2023/07/04 add user function
"""


import qdarkstyle 
from PyQt6 import QtCore, QtGui
from PyQt6.QtWidgets import QApplication, QVBoxLayout, QHBoxLayout, QMainWindow, QHeaderView
from PyQt6.QtWidgets import QWidget, QTableWidget, QTableWidgetItem, QAbstractItemView, QComboBox, QInputDialog
from PyQt6.QtGui import QAction
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt
from visu.WinCut import GRAPHCUT
from visu.winZoom import ZOOM
import pathlib
import numpy as np
import sys
import time
import os
from scipy import ndimage



class MEAS(QMainWindow):
    
    signalPlot = QtCore.pyqtSignal(object)
    
    def __init__(self, parent=None, conf=None, name='VISU', confMot=None, **kwds):
        
        super().__init__()

        self.parent = parent
        self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt6'))
        p = pathlib.Path(__file__)
        sepa = os.sep
        if conf is None:
            self.conf = QtCore.QSettings(str(p.parent / 'confVisu.ini'), QtCore.QSettings.IniFormat)
        else:
            self.conf = conf
        self.confMot = confMot   # le Qsetting des moteurs obsolete 
        self.name = name
        self.ThresholdState = False
        self.symbol = False
        
        if 'motRSAI' in kwds :
            self.motRSAI = kwds["motRSAI"]
            if self.motRSAI is True:
                import visu.moteurRSAISERVER as RSAI
                self.RSAI = RSAI
                self.listRack = self.RSAI.listRack()
                self.IPadress = self.listRack[0]
                self.rackName = []
                self.listMotorName = self.RSAI.listMotorName(self.IPadress)
                print('RSAI motor connected to python server')  
        else : 
            self.motRSAI = False
        
        if 'motA2V' in kwds :
            self.motA2V = kwds["motA2V"]
            if self.motA2V is True:
                # import importlib.utils
                # module_name = 'moteurA2V'
                sys.path.append('C:/Users/UPX/Desktop/python/camera')
                import moteurA2V as A2V
                self.A2V = A2V
                self.listRack = list()
                
                self.rackName = []
                self.listMotorName = self.A2V.listMotorName
                self.listMotor = self.A2V.listMotor
                print('TMCL motor connected to database')  
        else : 
            self.motA2V = False


        self.indexUnit = 1 # micron
        self.icon = str(p.parent) + sepa+'icons' + sepa
        self.isWinOpen = False
        self.setup()
        
        self.setWindowTitle('MEASUREMENTS')
        self.shoot = 0
        self.nomFichier = ' '
        self.TableSauv = ['file,Max,Min,x Max,y max,Sum,Mean,Size,x c.mass,y c.mass, user1']
        
        self.path = self.conf.value(self.name+"/path")
        self.winCoupeMax = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.winCoupeMin = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.winCoupeXmax = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.winCoupeYmax = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.winCoupeSum = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.winCoupeMean = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.winCoupeXcmass = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.winCoupeYcmass = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.winCoupeSumThreshold = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.winCoupeUser1 = GRAPHCUT(parent=self, conf=self.conf, name=self.name, symbol='t', pen=None,lastColored=True)
        self.signalTrans = dict()
        
        self.Maxx = []
        self.Minn = []
        self.Summ = []
        self.Mean = []
        self.Xmax = []
        self.Ymax = []
        self.Xcmass = []
        self.Ycmass = []
        self.labelsVert = []
        self.posMotor = []
        self.SummThre = []
        self.USER1 = []
        self.winZoomMax = ZOOM()
        self.winZoomSum = ZOOM()
        self.winZoomMean = ZOOM()
        self.winZoomXmax = ZOOM()
        self.winZoomYmax = ZOOM()
        self.winZoomCxmax = ZOOM()
        self.winZoomCymax = ZOOM()
        self.winZoomSumThreshold = ZOOM()
        self.winZoomUser1 = ZOOM()
        self.maxx = 0
        self.summ = 0
        self.moy = 0
        self.user1 = 0
        self.label = 'Shoot'
        self.setWindowIcon(QIcon(self.icon+'LOA.png'))
        self.setGeometry(100, 300, 1000, 300)
        if self.motRSAI is True or self.motA2V is True:
            self.stepmotor = 1
            self.unit()

    def setFile(self, file):
        self.nomFichier = file
        
    def setup(self):
            
        vLayout = QVBoxLayout()
        hLayout1 = QHBoxLayout()
        # self.toolBar  = self.addToolBar('tools')
        # self.setStyleSheet("{background-color: black}")
        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        self.fileMenu = menubar.addMenu('&File')
        self.PlotMenu = menubar.addMenu('&Plot')
        self.ZoomMenu = menubar.addMenu('&Zoom')
        
        self.ThresholdAct = QAction('Threshold', self)
        self.ThresholdMenu = menubar.addAction(self.ThresholdAct)
        self.ThresholdAct.triggered.connect(self.Threshold)
        
        self.setContentsMargins(0, 0, 0, 0)
       
        self.openAct = QAction(QtGui.QIcon(self.icon+"Open.png"), 'Open File', self)
        self.openAct.setShortcut('Ctrl+o')
        self.openAct.triggered.connect(self.openF)
        
        self.fileMenu.addAction(self.openAct)
        
        self.saveAct = QAction(QtGui.QIcon(self.icon+"disketteSave.png"), 'Save file', self)
        self.saveAct.setShortcut('Ctrl+s')
        self.saveAct.triggered.connect(self.saveF)
        
        self.fileMenu.addAction(self.saveAct)
        
        self.PlotMenu.addAction('max', self.PlotMAX)
        self.PlotMenu.addAction('min', self.PlotMIN)
        self.PlotMenu.addAction('x max', self.PlotXMAX)
        self.PlotMenu.addAction('y max', self.PlotYMAX)
        self.PlotMenu.addAction('Sum', self.PlotSUM)
        self.PlotMenu.addAction('Mean', self.PlotMEAN)
        self.PlotMenu.addAction('x center mass', self.PlotXCMASS)
        self.PlotMenu.addAction('y center mass', self.PlotYCMASS)
        self.PlotMenu.addAction('User 1', self.PlotUSER1)

        self.ZoomMenu.addAction('max', self.ZoomMAX)
        self.ZoomMenu.addAction('Sum', self.ZoomSUM)
        self.ZoomMenu.addAction('Mean', self.ZoomMEAN)
        self.ZoomMenu.addAction('X max', self.ZoomXmax) 
        self.ZoomMenu.addAction('Y max', self.ZoomYmax)
        self.ZoomMenu.addAction(' X c.of.m', self.ZoomCxmax)
        self.ZoomMenu.addAction(' Y c.of.m', self.ZoomCymax)
        self.ZoomMenu.addAction(' User1', self.ZoomUser1)
        
        self.But_reset = QAction('Reset', self)
        # self.PlotMenu.addAction(self.But_reset)
        menubar.addAction(self.But_reset)
        
        hLayout2 = QHBoxLayout()
        self.table = QTableWidget()
        hLayout2.addWidget(self.table)
        
        self.table.setColumnCount(12)
        # self.table.setRowCount(10)
       
        self.table.setHorizontalHeaderLabels(('File', 'Max', 'Min', 'x max', 'y max', 'Sum', 'Mean', 'Size', 'x c.mass', 'y c.mass', 'user1', 'date'))
        header = self.table.horizontalHeader()
        header.setDefaultAlignment(Qt.AlignmentFlag.AlignHCenter)
        header.setDefaultAlignment(Qt.AlignmentFlag.AlignVCenter)
        header.setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)

        if self.motRSAI is True or self.motA2V is True:
            self.motorNameBox = QComboBox()
            self.motorNameBox.addItem('Choose a Motor')
            self.unitBouton = QComboBox()
            self.unitBouton.addItem('Step')
            self.unitBouton.addItem('um')
            self.unitBouton.addItem('mm')
            self.unitBouton.addItem('ps')
            self.unitBouton.addItem('°')
            self.unitBouton.setMaximumWidth(100)
            self.unitBouton.setMinimumWidth(100)
            self.unitBouton.setCurrentIndex(self.indexUnit)
            hLayout1.addWidget(self.unitBouton)
            self.unitBouton.currentIndexChanged.connect(self.unit) 
            self.rackChoise = QComboBox()

            for rack in self.listRack: #
                self.rackChoise.addItem( str(self.RSAI.nameEquipment(rack))+ '  (' + rack +')')
            hLayout1.addWidget(self.rackChoise)
            self.motorNameBox.addItems(self.listMotorName)
            hLayout1.addWidget(self.motorNameBox)
            self.table.setColumnCount(13)   
            self.table.setHorizontalHeaderLabels(('File', 'Max', 'Min', 'x max', 'y max', 'Sum', 'Mean', 'Size', 'x c.mass', 'y c.mass', 'user1', 'Motor', 'date'))
            
            self.rackChoise.currentIndexChanged.connect(self.ChangeIPRack)
            self.motorNameBox.currentIndexChanged.connect(self.motorChange)
            
             
        self.table.horizontalHeader().setVisible(True)
        self.table.setAlternatingRowColors(True)
        self.table.resizeColumnsToContents()
        self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)  # no modifiableEditTriggers=QAbstractItemView.editTriggers(QAbstractItemView.NoEditTriggers)
        
        vLayout.addLayout(hLayout1)
        vLayout.addLayout(hLayout2)
        
        MainWidget = QWidget()
        MainWidget.setLayout(vLayout)
        self.setCentralWidget(MainWidget)
        self.setContentsMargins(1, 1, 1, 1)
        
        if self.parent is not None:
            self.parent.signalMeas.connect(self.Display)
            
        # if self.parent is not None:
        #     self.parent.newMesurment.connect(self.Display)
        self.But_reset.triggered.connect(self.Reset)
        
    def Reset(self):
        self.shoot = 0
        self.table.setRowCount(0)
        self.Maxx = []
        self.Minn = []
        self.Summ = []
        self.Mean = []
        self.Xmax = []
        self.Ymax = []
        self.Xcmass = []
        self.Ycmass = []
        self.labelsVert = []
        self.posMotor = []
        self.SummThre = []
        self.USER = []

    def saveF(self):
       
        fname = QtGui.QFileDialog.getSaveFileName(self, "Save Measurements as txt file", self.path)
        self.path = os.path.dirname(str(fname[0]))
        f = open(str(fname[0])+'.txt', 'w')
        f.write("\n".join(self.TableSauv))
        f.close()
        
    def openF(self):
        '''
        to do
        '''
        print('open not done yet')
    
    def ZoomMAX(self):
        self.open_widget(self.winZoomMax)
        self.winZoomMax.SetTITLE('MAX')
        self.winZoomMax.setZoom(self.maxx)
        
    def ZoomSUM(self):
        self.open_widget(self.winZoomSum)
        self.winZoomSum.SetTITLE('Sum')
        self.winZoomSum.setZoom(self.summ)
        
    def ZoomMEAN(self):
        self.open_widget(self.winZoomMean)
        self.winZoomMean.SetTITLE('Mean')
        self.winZoomMean.setZoom(self.moy)    
   
    def ZoomXmax(self):
        self.open_widget(self.winZoomXmax)
        self.winZoomXmax.SetTITLE('x max')
        self.winZoomXmax.setZoom(self.xmax)
        
    def ZoomYmax(self):
        self.open_widget(self.winZoomYmax)
        self.winZoomYmax.SetTITLE('y max')
        self.winZoomYmax.setZoom(self.ymax) 
    
    def ZoomCxmax(self):
        self.open_widget(self.winZoomCymax)
        self.winZoomCxmax.SetTITLE('x center of mass')
        self.winZoomCxmax.setZoom(self.xcmass)   
    
    def ZoomCymax(self):
        self.open_widget(self.winZoomCxmax)
        self.winZoomCymax.SetTITLE('y center of mass')
        self.winZoomCymax.setZoom(self.ycmass)
        
    def ZoomSUMThreshold(self):
        self.open_widget(self.winZoomSumThreshold)
        
        self.winZoomSumThreshold.SetTITLE('Sum threshold')
        self.winZoomSumThreshold.setZoom(self.summThre) 
    
    def ZoomUser1(self):
        self.open_widget(self.winZoomUser1)
        
        self.winZoomUser1.SetTITLE('User 1')
        self.winZoomUser1.setZoom(self.user1)

    def PlotMAX(self):
        self.open_widget(self.winCoupeMax)
        self.winCoupeMax.SetTITLE('Plot Max')
        self.signalTrans['data'] = self.Maxx
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
        
        self.signalPlot.emit(self.signalTrans)
        # self.winCoupeMax.PLOT(self.Maxx,axis = self.posMotor, label = self.label)
    
    def PlotMIN(self):
        self.open_widget(self.winCoupeMin)
        self.winCoupeMin.SetTITLE('Plot Min')
        self.signalTrans['data'] = self.Minn
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
        
        self.signalPlot.emit(self.signalTrans)
        # self.winCoupeMin.PLOT(self.Minn,axis = self.posMotor,label = self.label)
        
    def PlotXMAX(self):
        self.open_widget(self.winCoupeXmax)
        self.winCoupeXmax.SetTITLE('Plot  X MAX')
        self.signalTrans['data'] = self.Xmax
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
        
        self.signalPlot.emit(self.signalTrans)
        
        # self.winCoupeXmax.PLOT(self.Xmax,axis = self.posMotor,label = self.label)
    
    def PlotYMAX(self):
        self.open_widget(self.winCoupeYmax)
        self.winCoupeYmax.SetTITLE('Plot  Y MAX')
        self.signalTrans['data'] = self.Ymax
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
        
        self.signalPlot.emit(self.signalTrans)
        # self.winCoupeYmax.PLOT(self.Ymax,axis = self.posMotor,label = self.label)
     
    def PlotSUM(self):
        self.open_widget(self.winCoupeSum)
        self.winCoupeSum.SetTITLE('Plot Sum')
        self.signalTrans['data'] = self.Summ
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
        
        self.signalPlot.emit(self.signalTrans)
        # self.winCoupeSum.PLOT(self.Summ,axis = self.posMotor,label = self.label)
    
    def PlotMEAN(self):
        self.open_widget(self.winCoupeMean)
        self.winCoupeMean.SetTITLE('Plot Mean')
        self.signalTrans['data'] = self.Mean
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
        
        self.signalPlot.emit(self.signalTrans)
        # self.winCoupeMean.PLOT(self.Mean,axis = self.posMotor,label = self.label)
        
    def PlotXCMASS(self):
        self.open_widget(self.winCoupeXcmass)
        self.winCoupeXcmass.SetTITLE('Plot x center of mass')
        self.signalTrans['data'] = self.Xcmass
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
        
        self.signalPlot.emit(self.signalTrans)
        # self.winCoupeXcmass.PLOT(self.Xcmass,axis = self.posMotor,label = self.label)
    
    def PlotYCMASS(self):
        self.open_widget(self.winCoupeYcmass)
        self.winCoupeYcmass.SetTITLE('Plot Y center of mass')
        self.signalTrans['data'] = self.Ycmass
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
        
        self.signalPlot.emit(self.signalTrans)
        # self.winCoupeYcmass.PLOT(self.Xcmass,axis = self.posMotor,label = self.label)    
    
    def PlotSUMTHRESHOLD(self):
        self.open_widget(self.winCoupeSumThreshold)
        self.winCoupeSumThreshold.SetTITLE('Plot Sum with Threshold')
        # print('fct',self.SummThre,self.posMotor)
        self.signalTrans['data'] = self.SummThre
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
       
        self.signalPlot.emit(self.signalTrans)
    
    def Threshold(self):
        
        threshold, ok = QInputDialog.getInt(self, 'Threshold Filter ', 'Enter thresold value')
        if ok:
            self.ThresholdState = True
            self.threshold = threshold
            self.Reset()
            self.PlotMenu.addAction('Sum Threshold', self.PlotSUMTHRESHOLD)
            self.ZoomMenu.addAction(' Sum  with Threshold', self.ZoomSUMThreshold)
            self.Display(self.data)
        else:
            self.ThresholdState = False
            self.PlotMenu.removeAction('Sum Threshold', self.PlotSUMTHRESHOLD)
            self.ZoomMenu.removeAction(' Sum  with Threshold', self.ZoomSUMThreshold)

    def PlotUSER1(self):
        self.openwidget(self.winCoupeUser1)
        self.winCoupeUser1.SetTITLE('User1')
        self.signalTrans['data'] = self.USER1
        self.signalTrans['axis'] = self.posMotor
        self.signalTrans['label'] = self.label
        
        self.signalPlot.emit(self.signalTrans)

    def Display(self, data):
        self.data = data[0]
        self.transx=data[1]
        self.transy=data[2]
        self.scalex=data[3]
        self.scaley=data[4]
        
        #print(self.transx,self.scaley)
        self.maxx = round(self.data.max(), 3)
        self.minn = round(self.data.min(), 3)
        self.summ = round(self.data.sum(), 3)
        self.moy = round(self.data.mean(), 3)
        self.user1 = round(self.FctUser1(), 3)
        self.date = time.strftime("%Y_%m_%d_%H_%M_%S")
        
        (self.xmax, self.ymax) = np.unravel_index(self.data.argmax(), self.data.shape)
        self.xmax = (self.xmax + self.transx) * self.scalex 
        self.ymax = (self.ymax  + self.transy) * self.scaley 
        # print(self.maxx,data[int(self.xmax),int(self.ymax)])
        (self.xcmass, self.ycmass) = ndimage.center_of_mass(self.data)
        self.xcmass = (round(self.xcmass, 3) + self.transx) *self.scalex
        self.ycmass = (round(self.ycmass, 3) + self.transy) *self.scaley
        
        self.xs = self.data.shape[0]
        self.ys = self.data.shape[1]
        self.table.setRowCount(self.shoot+1)
        self.table.setItem(self.shoot, 0, QTableWidgetItem(str(self.nomFichier)))
        self.table.setItem(self.shoot, 1, QTableWidgetItem(str(self.maxx)))
        self.table.setItem(self.shoot, 2, QTableWidgetItem(str(self.minn)))
        self.table.setItem(self.shoot, 3, QTableWidgetItem(str(self.xmax)))
        self.table.setItem(self.shoot, 4, QTableWidgetItem(str(self.ymax)))
        self.table.setItem(self.shoot, 5, QTableWidgetItem("{:.3e}".format(self.summ)))
        self.table.setItem(self.shoot, 6, QTableWidgetItem(str(self.moy)))
        self.table.setItem(self.shoot, 7, QTableWidgetItem((str(self.xs) + '*' + str(self.ys))))
        self.table.setItem(self.shoot, 8, QTableWidgetItem(str(self.xcmass)))
        self.table.setItem(self.shoot, 9, QTableWidgetItem(str(self.ycmass)))
        self.table.setItem(self.shoot, 10, QTableWidgetItem(str(self.user1)))

        if self.motRSAI is True or self.motA2V is True :
            if self.motorNameBox.currentIndex() ==0 :
                Posi = self.shoot
                self.label = 'Shoot'
            else:
                Posi = round((self.MOT.position())/self.unitChange,2)
                
                self.label = self.MOT.name + '  ( '+self.unitName+' )'
        
        else:
            Posi = self.shoot
            self.label = 'Shoot'
            
        self.posMotor.append(Posi)    
        self.table.resizeColumnsToContents()
        self.labelsVert.append('%s' % self.shoot)
        
        if self.ThresholdState is True:
            dataCor = np.where(self.data < self.threshold, 0, data)
            self.summThre = round(dataCor.sum(), 3)
            self.SummThre.append(self.summThre)
            self.TableSauv.append('%s,%.1f,%.1f,%i,%i,%.1f,%.3f,%.2f,%.2f,%.2f, %.2f,%.2f,%.2f,%.2f,%s' % (self.nomFichier, self.maxx, self.minn, self.xmax, self.ymax, self.summ, self.moy, self.xs, self.ys, self.xcmass, self.ycmass, Posi, self.summThre, self.user1, self.date))
            
            if self.motRSAI is True or self.motA2V is True:
                self.table.setColumnCount(14)
                self.table.setHorizontalHeaderLabels(('File', 'Max', 'Min', 'x max', 'y max', 'Sum Mean', 'Size', 'x c.mass', 'y c.mass', 'Sum Thr', ' Motor', 'date'))
                self.table.setItem(self.shoot, 12, QTableWidgetItem(str(Posi)))
                self.table.setItem(self.shoot, 13, QTableWidgetItem(str(self.date)))
            else:
                self.table.setColumnCount(13)
                self.table.setHorizontalHeaderLabels(('File', 'Max', 'Min', 'x max', 'y max', 'Sum', 'Mean', 'Size', 'x c.mass', 'y c.mass', 'Sum Thr', 'user1', 'date'))
                self.TableSauv = ['file,Max,Min,x Max,y max,Sum,Mean,Size,x c.mass, y c.mass,SumCorr,date']
                self.table.setItem(self.shoot, 11, QTableWidgetItem(str(self.date)))
            self.table.setItem(self.shoot, 10, QTableWidgetItem("{:.3e}".format(self.summThre)))
            
        else:
            self.TableSauv.append('%s,%.1f,%.1f,%i,%i,%.1f,%.3f,%.2f,%.2f,%.2f, %.2f,%.2f,%.2f,%s' % (self.nomFichier, self.maxx, self.minn, self.xmax, self.ymax, self.summ, self.moy, self.xs, self.ys, self.xcmass, self.ycmass, self.user1, Posi, self.date))
            
            if self.motRSAI is True or self.motA2V is True:
                self.table.setHorizontalHeaderLabels(('File', 'Max', 'Min', 'x max', 'y max', 'Sum', 'Mean', 'Size', 'x c.mass', 'y c.mass', 'user1', 'Motor', 'date'))
                self.table.setColumnCount(13)
                self.table.setItem(self.shoot, 11, QTableWidgetItem(str(Posi)))
                self.table.setItem(self.shoot, 12, QTableWidgetItem(str(self.date)))
            else:
                self.table.setHorizontalHeaderLabels(('File', 'Max', 'Min', 'x max', 'y max', 'Sum', 'Mean', 'Size', 'x c.mass', 'y c.mass', 'user1', 'date'))
                self.table.setColumnCount(12)
                self.table.setItem(self.shoot, 11, QTableWidgetItem(str(self.date)))
        
        self.table.selectRow(self.shoot)
        self.Maxx.append(self.maxx)
        self.Minn.append(self.minn)
        self.Summ.append(self.summ)
        self.Mean.append(self.moy)
        self.Xmax.append(self.xmax)
        self.Ymax.append(self.ymax)
        self.Xcmass.append(self.xcmass)
        self.Ycmass.append(self.ycmass)
        self.USER1.append(self.user1)

        self.table.setVerticalHeaderLabels(self.labelsVert)

        #  plot Update plot
        if self.winCoupeMax.isWinOpen is True:
            self.PlotMAX()  # (self.Maxx,axis=self.posMotor,symbol = self.symbol, pen=None,label=self.motor)
        if self.winCoupeMin.isWinOpen is True:
            self.PlotMIN()
        if self.winCoupeXmax.isWinOpen is True:
            self.PlotXMAX()
        if self.winCoupeYmax.isWinOpen is True:
            self.PlotYMAX()
        if self.winCoupeSum.isWinOpen is True:
            self.PlotSUM()
        if self.winCoupeMean.isWinOpen is True:
            self.PlotMEAN()
        if self.winCoupeXcmass.isWinOpen is True:
            self.PlotXCMASS()
        if self.winCoupeYcmass.isWinOpen is True:
            self.PlotYCMASS()
        if self.winCoupeSumThreshold.isWinOpen is True:
            self.PlotSUMTHRESHOLD()
        if self.winCoupeUser1.isWinOpen is True:
            self.PlotUSER1()

        # update zoom windows  
        if self.winZoomMax.isWinOpen is True:
            self.ZoomMAX()
        if self.winZoomSum.isWinOpen is True:
            self.ZoomSUM()
        if self.winZoomMean.isWinOpen is True:
            self.ZoomMEAN() 
        if self.winZoomXmax.isWinOpen is True:
            self.ZoomXmaX()
        if self.winZoomYmax.isWinOpen is True:
            self.ZoomYmAX()
        if self.winZoomCxmax.isWinOpen is True:
            self.ZoomCxmaX()
        if self.winZoomCymax.isWinOpen is True:
            self.ZoomCymAX()   
        if self.winZoomSumThreshold.isWinOpen is True:
            self.ZoomSUMThreshold()
        if self.winZoomUser1.isWinOpen is True:
            self.ZoomUser1()   
        self.shoot += 1
      
    def closeEvent(self, event):
        """ when closing the window
        """
        self.isWinOpen = False
        self.shoot = 0
        self.TableSauv = ['file,Max,Min,x Max,y max,Sum,Mean,Size,x c.mass,y c.mass']
        
        if self.winCoupeMax.isWinOpen is True:
            self.winCoupeMax.close()
        if self.winCoupeMin.isWinOpen is True:
            self.winCoupeMin.close()
        if self.winCoupeXmax.isWinOpen is True:
            self.winCoupeXmax.close()
        if self.winCoupeYmax.isWinOpen is True:
            self.winCoupeYmax.close()
        if self.winCoupeSum.isWinOpen is True:
            self.winCoupeSum.close()
        if self.winCoupeMean.isWinOpen is True:
            self.winCoupeMean.close()
        if self.winCoupeXcmass.isWinOpen is True:
            self.winCoupeXcmass.close()
        if self.winCoupeYcmass.isWinOpen is True:
            self.winCoupeYcmass.close()
        if self.winCoupeSumThreshold.isWinOpen is True:
            self.winCoupeSumThreshold.close()
        time.sleep(0.1)
        event.accept()

    def open_widget(self, fene):
        """ ouverture widget suplementaire
        """

        if fene.isWinOpen is False:
            fene.setup
            fene.isWinOpen = True
            # A=self.geometry()
            # fene.setGeometry(A.left()+A.width(),A.top(),500,A.height())
            fene.show()
        else:
            # fene.activateWindow()
            # fene.raise_()
            fene.showNormal()

    def FctUser1(self):
        # The USER1 function
        a = 0  # 10*random()
        
        return (a)

    def motorChange(self):
        if self.motorNameBox.currentIndex() != 0 :
            self.numMotor = self.motorNameBox.currentIndex()
            
            if self.motA2V is True:
                self.numMotor = self.numMotor -1
                self.MOT = self.A2V.MOTORA2V(self.listMotor[self.numMotor])
                self.stepmotor = self.MOT.step
            if self.motRSAI is True :
                self.IPadress = self.listRack [self.rackChoise.currentIndex()]
                self.MOT = self.RSAI.MOTORRSAI(self.IPadress, self.numMotor)
                self.stepmotor = self.MOT.step
               
            
            self.unit()
        

    def ChangeIPRack(self):
        self.motorNameBox.clear()
        self.IPadress = str( self.listRack[self.rackChoise.currentIndex()])
        #print('ip',self.IPadress)
        self.listMotorName = self.RSAI.listMotorName(self.IPadress)
        #print('listmotorname',self.listMotorName)
        self.rackName = self.RSAI.nameEquipment(self.IPadress)
        self.motorNameBox.addItem('Choose a motor')
        self.motorNameBox.addItems(self.listMotorName)

    def unit(self):
        '''
        unit change mot foc
        '''
        self.indexUnit = self.unitBouton.currentIndex()
        #print('winMeas',self.stepmotor)
        if self.indexUnit == 0:  # step
            self.unitChange = 1
            self.unitName = 'step'
            
        if self.indexUnit == 1:  # micron
            self.unitChange = float((1*self.stepmotor))
            self.unitName = 'um'
        if self.indexUnit == 2:  # mm
            self.unitChange = float((1000*self.stepmotor))
            self.unitName = 'mm'
        if self.indexUnit == 3:  # ps  double passage : 1 microns=6fs
            self.unitChange = float(1*self.stepmotor/0.0066666666)
            self.unitName = ' ps'
        if self.indexUnit == 4:  # en degres
            self.unitChange = 1 * self.stepmotor
            self.unitName = '°'
        
        if self.unitChange == 0:
            self.unitChange = 1  # avoid /0


if __name__ == "__main__":
    appli = QApplication(sys.argv)
    appli.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt6'))
    e = MEAS(motRSAI=True)
    e.show()
    appli.exec_()