from AppliDef import *


class FrmTabRecapMat(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.ClassListe = []
        self.StringClass = tk.StringVar()
        self.ListClass = None
        self.ListMat = []
        self.TabMat = None
        self.TypeTri = ''
        self.ClassList = []
        self.TitreClass = ''
        self.LClass = 0
        self.TriPar = False
        self.CanvasBtnRetour, self.ImgBtnRetour, self.ImgCanvasBtnRetour = None, None, None
        self.EntryManuelVal = None
        self.ListModif = []
        self.ParaTabMat = []
        self.Lieu = ""
        self.Salle = ''
        self.Quant = ''
        self.Salle2 = ''
        self.Quant2 = ''
        self.MenuClicDroit = []
        self.NMatSelect = 0

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmAjout/Fond/Fond.jpg')
        self.SX = int((float(FrmFond.size[0]) * float(self.RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(self.RatioY)))

        coefY = float(ConfigResolution(self.MainAppli.Nconfig, 'YTitreFrm', self.MainAppli.curSave))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmAjout/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.002)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.031)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        self.ImgBtnClose, wsize, hsize, self.CanvasBtnClose, self.ImgCanvasBtnClose = CanInWindow(
            'Media/FrmAjout/BtnClose/', self.RatioX, self.RatioY, self.CanvasFrmFond, tk.CENTER,
            int(self.SX * 0.988), int(self.SY * 0.014), 0)
        ChangeCursor(self.CanvasBtnClose)
        self.CanvasBtnClose.bind('<Motion>',
                                 lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                               image=self.ImgBtnClose[1]))
        self.CanvasBtnClose.bind('<ButtonRelease-1>', self.CacheFrmTabRecapMat)

        Titre = ''
        if self.MainAppli.BaseEnCours == "CHIMIE":
            Titre = 'Tableau récapitulatif du matériel de chimie en stock'
            self.Lieux = self.MainAppli.LieuxStockMatChim
        elif self.MainAppli.BaseEnCours == "PHYS":
            Titre = 'Tableau récapitulatif du matériel de physique en stock'
            self.Lieux = self.MainAppli.LieuxStockMatPhys
        self.LabelTag = LabelInCanvas(self.CanvasFrmFond, Titre, '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)

        LabelInCanvas(self.CanvasFrmFond, 'Tri par: ', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0), int(self.SX * 0.88),
                      int(self.SY * coefY), tk.NE)

        self.TriListe = ['Ordre alphabétique', 'Lieux de stockage', 'Catégories', 'Fournisseurs']
        self.StringTri = tk.StringVar()
        self.StringTri.set(self.TriListe[0])
        self.ListTri = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.01), textvariable=self.StringTri,
                                       values=self.TriListe)
        self.CanvasFrmFond.create_window(int(self.SX * 0.88), int(self.SY * coefY), anchor=tk.NW,
                                         window=self.ListTri)
        self.ListTri.bind('<<ComboboxSelected>>', self.ActionAffichTabRecapMat)

        self.BtnPrint = BtnAction(self.CanvasFrmFond, int(self.SX * 0.965),
                                  int(self.SY * 0.014), self.RatioX, self.RatioX, 'Media/Divers/BtnPrint/')
        self.BtnPrint.CanvasBtn.bind('<ButtonRelease-1>', self.Imprim)

        self.CanvasMenu = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.995),
                                     int(self.SY * 0.965), int(self.SX * 0.003), int(self.SY * 0.031), tk.NW)

        self.AffichTabRecapMat()

        self.CanvasFrmFond.focus_set()
        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)

        self.CanvasFrmFond.pack()

    def ActionAffichTabRecapMat(self, _):
        self.AffichTabRecapMat()

    def AffichTabRecapMat(self):
        self.EffaceMenu()
        if self.StringTri.get() == 'Ordre alphabétique':
            self.TriPar = False
            if self.MainAppli.BaseEnCours == "CHIMIE":
                requet = "select " + "NOMS, LABOLIEU, LABOQUANT, LABOLIEU2, LABOQUANT2, SALLETPLIEU, SALLETPQUANT, " \
                                     "POSTETPLIEU, POSTETPQUANT, SPECTROLIEU, SPECTROQUANT, QSTOCK, QUtil" \
                         + " from MATERIEL order by NOMS"
                self.MainAppli.cur.execute(requet)
                self.ListMat = self.MainAppli.cur.fetchall()
                self.ParaTabMat = ['Matériels de chimie classés par ordre alphabétique', 13,
                                   ['Noms', self.Lieux[0], 'Quantité', self.Lieux[0], 'Quantité', self.Lieux[1],
                                    'Quantité', self.Lieux[1], 'Quantité', self.Lieux[2], 'Quantité',
                                    'Quantité totale\nen stock', 'Quantité utilisée\n / an'],
                                   [0.034, 0.009, 0.005, 0.009, 0.005, 0.009, 0.005, 0.009, 0.005, 0.009, 0.005, 0.007,
                                    0.007]]
            elif self.MainAppli.BaseEnCours == "PHYS":
                requet = "select " + "NOMS, LaboLieu, LaboQuant, SalleTPLieu, SalleTPQuant, " \
                                     "ResLIEU, ResQUANT,  QUtil" + " from MATERIEL order by NOMS"
                self.MainAppli.curphys.execute(requet)
                self.ListMat = self.MainAppli.curphys.fetchall()
                ListMat = []
                for i in range(len(self.ListMat)):
                    ListMat.append(list(self.ListMat[i]))
                self.ListMat = list(ListMat)
                for i in range(len(self.ListMat)):
                    QStock = 0
                    if self.ListMat[i][2] != '' and self.ListMat[i][2] is not None:
                        QStock = QStock + int(self.ListMat[i][2])
                    if self.ListMat[i][4] != '' and self.ListMat[i][4] is not None:
                        QStock = QStock + int(self.ListMat[i][4])
                    if self.ListMat[i][6] != '' and self.ListMat[i][6] is not None:
                        QStock = QStock + int(self.ListMat[i][6])
                    self.ListMat[i].append(str(QStock))
                    self.ListMat[i][7], self.ListMat[i][8] = self.ListMat[i][8], self.ListMat[i][7]

                self.ParaTabMat = ['Matériels de physique classés par ordre alphabétique', 9,
                                   ['Noms', self.Lieux[0], 'Quantité', self.Lieux[1], 'Quantité', self.Lieux[2],
                                    'Quantité', 'Quantité totale\nen stock', 'Quantité utilisée\n / an'],
                                   [0.047, 0.012, 0.007, 0.012, 0.007, 0.012, 0.007, 0.007, 0.007]]

            self.TabMat = AffichTabMultiPage(self.CanvasMenu.CanvasMenu, self.ListMat, 40,
                                             self.ParaTabMat[0], self.MainAppli.SizeFont, self.ParaTabMat[1],
                                             self.ParaTabMat[2], self.ParaTabMat[3], self)
            self.ActivModifTab()

        elif self.StringTri.get() == 'Lieux de stockage':
            self.TriPar = True
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.TitreClass = 'Matériels de chimie classés par lieu de stockage:'
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.TitreClass = 'Matériels de Physique classés par lieu de stockage:'
            self.LClass = 0.018
            self.AffichListClass(3)
        elif self.StringTri.get() == 'Catégories':
            self.TriPar = True
            self.TypeTri = "CATEGORIE"
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.TitreClass = 'Matériels de chimie classés par catégorie:'
                self.LClass = 0.015
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.TitreClass = 'Matériels de physique classés par catégorie:'
                self.LClass = 0.025
            self.AffichListClass(2)
        elif self.StringTri.get() == 'Fournisseurs':
            self.TriPar = True
            self.TypeTri = "FOURNISSEUR"
            self.LClass = 0.015
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.TitreClass = 'Matériels de chimie classés par fournisseur:'
                self.AffichListClass(15)
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.TitreClass = 'Matériels de physique classés par fournisseur:'
                self.AffichListClass(10)

    def AffichSelectListClass(self, L):
        self.ListClass = ListeDeroulante(self.CanvasMenu.CanvasMenu,
                                         int(int(self.CanvasMenu.CanvasMenu['width']) * L),
                                         textvariable=self.StringClass,
                                         values=self.ClassList)
        self.CanvasMenu.CanvasMenu.create_window(int(int(self.CanvasMenu.CanvasMenu['width']) * 0.2),
                                                 int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004),
                                                 anchor=tk.NW,
                                                 window=self.ListClass)
        self.ListClass.bind('<<ComboboxSelected>>', self.ActionTriMat)

    def AffichListClass(self, IndexClass):
        self.EffaceMenu()
        self.ClassListe = []
        self.ClassList = []
        if self.StringTri.get() == 'Lieux de stockage':
            for i in range(len(self.MainAppli.ListMats)):
                if self.MainAppli.ListMats[i][IndexClass] != '' \
                        and self.MainAppli.ListMats[i][IndexClass] not in self.ClassListe:
                    self.ClassListe.append(self.MainAppli.ListMats[i][IndexClass])
                if self.MainAppli.BaseEnCours == "CHIMIE":
                    if self.MainAppli.ListMats[i][IndexClass + 2] != '' \
                            and self.MainAppli.ListMats[i][IndexClass + 2] not in self.ClassListe:
                        self.ClassListe.append(self.MainAppli.ListMats[i][IndexClass + 2])
            self.ClassListe.sort()
            for i in range(len(self.ClassListe)):
                self.ClassList.append(self.Lieux[0] + " - " + self.ClassListe[i])
            self.ClassListe = []
            SIndex = 0
            if self.MainAppli.BaseEnCours == "CHIMIE":
                SIndex = 4
            elif self.MainAppli.BaseEnCours == "PHYS":
                SIndex = 2
            for i in range(len(self.MainAppli.ListMats)):
                if self.MainAppli.ListMats[i][IndexClass + SIndex] != '' \
                        and self.MainAppli.ListMats[i][IndexClass + SIndex] not in self.ClassListe:
                    self.ClassListe.append(self.MainAppli.ListMats[i][IndexClass + SIndex])
                if self.MainAppli.BaseEnCours == "CHIMIE":
                    if self.MainAppli.ListMats[i][IndexClass + SIndex + 2] != '' \
                            and self.MainAppli.ListMats[i][IndexClass + SIndex + 2] not in self.ClassListe:
                        self.ClassListe.append(self.MainAppli.ListMats[i][IndexClass + SIndex + 2])
            self.ClassListe.sort()
            for i in range(len(self.ClassListe)):
                self.ClassList.append(self.Lieux[1] + " - " + self.ClassListe[i])
            self.ClassListe = []
            SIndex = 0
            if self.MainAppli.BaseEnCours == "CHIMIE":
                SIndex = 8
            elif self.MainAppli.BaseEnCours == "PHYS":
                SIndex = 4
            for i in range(len(self.MainAppli.ListMats)):
                if self.MainAppli.ListMats[i][IndexClass + SIndex] != '' \
                        and self.MainAppli.ListMats[i][IndexClass + SIndex] not in self.ClassListe:
                    self.ClassListe.append(self.MainAppli.ListMats[i][IndexClass + SIndex])
            self.ClassListe.sort()
            for i in range(len(self.ClassListe)):
                self.ClassList.append(self.Lieux[2] + " - " + self.ClassListe[i])
            if len(self.ClassList) > 0:
                self.StringClass.set(self.ClassList[0])

        else:
            self.ClassList = []
            for i in range(len(self.MainAppli.ListMats)):
                if self.MainAppli.ListMats[i][IndexClass] not in self.ClassList:
                    self.ClassList.append(self.MainAppli.ListMats[i][IndexClass])
            for i in range(len(self.ClassList)):
                if self.ClassList[i] == "":
                    self.ClassList[i] = "Sans"
            if len(self.ClassList) > 0:
                self.ClassList.sort()
                self.StringClass.set(self.ClassList[0])

        self.TriMat()

    def ActionTriMat(self, _):
        self.EffaceMenu()
        self.TriMat()

    def TriMat(self):
        self.AffichSelectListClass(self.LClass)
        if self.StringTri.get() == 'Lieux de stockage':
            if self.StringClass.get() != '':
                listLieu = self.StringClass.get().split("-", 2)
                self.Salle = listLieu[0].replace(' ', '')
                self.Lieu = listLieu[1].lstrip()
                if self.MainAppli.BaseEnCours == "CHIMIE":
                    self.Salle2 = ''
                    self.Quant = ""
                    self.Quant2 = ""
                    if self.Salle == self.Lieux[0].replace(' ', ''):
                        self.Salle = "LABOLIEU"
                        self.Salle2 = "LABOLIEU2"
                        self.Quant = "LABOQUANT"
                        self.Quant2 = "LABOQUANT2"
                    if self.Salle == self.Lieux[1].replace(' ', ''):
                        self.Salle = "SALLETPLIEU"
                        self.Salle2 = "POSTETPLIEU"
                        self.Quant = "SALLETPQUANT"
                        self.Quant2 = "POSTETPQUANT"
                    if self.Salle == self.Lieux[2].replace(' ', ''):
                        self.Salle = "SPECTROLIEU"
                        self.Salle2 = "SPECTROLIEU"
                        self.Quant = "SPECTROQUANT"
                        self.Quant2 = "SPECTROQUANT"
                    self.MainAppli.cur.execute("SELECT " + "NOMS, CATEGORIE, " + self.Quant +
                                               " FROM MATERIEL WHERE " + self.Salle + " = \"" + self.Lieu
                                               + "\" order by NOMS")
                    ListMat1 = self.MainAppli.cur.fetchall()
                    if self.Salle2 != "SPECTROLIEU":
                        self.MainAppli.cur.execute("SELECT " + "NOMS, CATEGORIE, " + self.Quant2 +
                                                   " FROM MATERIEL WHERE " + self.Salle2 + " = \"" + self.Lieu +
                                                   "\" order by NOMS")
                        ListMat2 = self.MainAppli.cur.fetchall()
                    else:
                        ListMat2 = []
                    self.ListMat = ListMat1 + ListMat2
                    self.ListMat.sort()
                elif self.MainAppli.BaseEnCours == "PHYS":
                    self.Quant = ""
                    if self.Salle == self.Lieux[0].replace(' ', ''):
                        self.Salle = "LaboLieu"
                        self.Quant = "LaboQuant"
                    if self.Salle == self.Lieux[1].replace(' ', ''):
                        self.Salle = "SalleTPLieu"
                        self.Quant = "SalleTPQuant"
                    if self.Salle == self.Lieux[2].replace(' ', ''):
                        self.Salle = "ResLieu"
                        self.Quant = "ResQuant"
                    self.MainAppli.curphys.execute(
                        "SELECT " + "NOMS, CATEGORIE, " + self.Quant + " FROM MATERIEL WHERE "
                        + self.Salle + " = \"" + self.Lieu + "\" order by NOMS")
                    self.ListMat = self.MainAppli.curphys.fetchall()

            self.ParaTabMat = [3, ['Noms', 'Catégorie', 'Quantité en stock'], [0.04, 0.034, 0.014]]

            self.TabMat = AffichTabMultiPage(self.CanvasMenu.CanvasMenu, self.ListMat, 40,
                                             self.TitreClass, self.MainAppli.SizeFont, self.ParaTabMat[0],
                                             self.ParaTabMat[1], self.ParaTabMat[2], self)
            self.ActivModifTab()
        else:
            if self.StringClass.get() == "Sans":
                ChClass = ''
            else:
                ChClass = self.StringClass.get()
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.MainAppli.cur.execute("select "
                                           + "NOMS, LABOLIEU, LABOQUANT, LABOLIEU2, LABOQUANT2, SALLETPLIEU, "
                                             "SALLETPQUANT, POSTETPLIEU, POSTETPQUANT, SPECTROLIEU, SPECTROQUANT, "
                                             " QSTOCK, QUtil" + " from MATERIEL WHERE " + self.TypeTri + " = \""
                                           + ChClass + "\" order by NOMS")
                self.ListMat = self.MainAppli.cur.fetchall()
                self.ParaTabMat = [13, ['Noms', self.Lieux[0], 'Quantité', self.Lieux[0], 'Quantité', self.Lieux[1],
                                        'Quantité', self.Lieux[1], 'Quantité', self.Lieux[2], 'Quantité',
                                        'Quantité totale\nen stock', 'Quantité utilisée\n / an'],
                                   [0.034, 0.009, 0.005, 0.009, 0.005, 0.009, 0.005, 0.009, 0.005, 0.009, 0.005, 0.007,
                                    0.007]]
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.MainAppli.curphys.execute("select " + "NOMS, LaboLieu, LaboQuant, SalleTPLieu, SalleTPQuant, "
                                                           "ResLIEU, ResQUANT, QUtil" + " from MATERIEL WHERE "
                                               + self.TypeTri + " = \"" + ChClass + "\" order by NOMS")
                self.ListMat = self.MainAppli.curphys.fetchall()
                ListMat = []
                for i in range(len(self.ListMat)):
                    ListMat.append(list(self.ListMat[i]))
                self.ListMat = list(ListMat)
                for i in range(len(self.ListMat)):
                    QStock = 0
                    if self.ListMat[i][2] != '' and self.ListMat[i][2] is not None:
                        QStock = QStock + int(self.ListMat[i][2])
                    if self.ListMat[i][4] != '' and self.ListMat[i][4] is not None:
                        QStock = QStock + int(self.ListMat[i][4])
                    if self.ListMat[i][6] != '' and self.ListMat[i][6] is not None:
                        QStock = QStock + int(self.ListMat[i][6])
                    self.ListMat[i].append(str(QStock))
                    self.ListMat[i][7], self.ListMat[i][8] = self.ListMat[i][8], self.ListMat[i][7]
                self.ParaTabMat = [9, ['Noms', self.Lieux[0], 'Quantité', self.Lieux[1], 'Quantité', self.Lieux[2],
                                       'Quantité', 'Quantité totale\nen stock', 'Quantité utilisée\n / an'],
                                   [0.047, 0.012, 0.007, 0.012, 0.007, 0.012, 0.007, 0.007, 0.007]]

            self.TabMat = AffichTabMultiPage(self.CanvasMenu.CanvasMenu, self.ListMat, 40,
                                             self.TitreClass, self.MainAppli.SizeFont, self.ParaTabMat[0],
                                             self.ParaTabMat[1], self.ParaTabMat[2], self)
            self.ActivModifTab()

    def EffaceMenu(self):
        for widget in self.CanvasMenu.CanvasMenu.winfo_children():
            widget.destroy()

    def Imprim(self, _):
        self.BtnPrint.CanvasBtn.itemconfig(self.BtnPrint.ImgCanvasBtn, image=self.BtnPrint.ImgBtn[0])
        FileToImprim = Imprim(self.CanvasMenu.CanvasMenu, 'Datas/Print/', 'tmp.bmp')
        if self.MainAppli.BaseEnCours == "CHIMIE":
            AffichPDF('Tableau récapitulatif du matériel de chimie en stock', FileToImprim, self)
        elif self.MainAppli.BaseEnCours == "PHYS":
            AffichPDF('Tableau récapitulatif du matériel de physique en stock', FileToImprim, self)
        self.MainAppli.parent.lift()
        self.lift()
        self.CanvasFrmFond.focus_set()

    def ActivModifTab(self):
        for l in range(self.TabMat.TabMat.NLine):
            for k in range(self.TabMat.TabMat.NCol):
                def GestEvt(evt, Line=l, Col=k):
                    return self.ModifVal(evt, Line, Col)

                def GestEvt2(evt):
                    return self.AnnulModifVal(evt)

                def GestEvt4(evt, L=l):
                    return self.ActionIndexMat(evt, L)

                if k > 0:
                    self.TabMat.TabMat.TabLabels[l][k].bind('<Double-1>', GestEvt)
                    self.TabMat.TabMat.TabLabels[l][k].bind('<Button-1>', GestEvt2)
                else:
                    self.TabMat.TabMat.TabLabels[l][0].bind('<Double-1>', GestEvt4)

        if len(self.ListMat) > 0:
            for C in range(self.TabMat.TabMat.NCol):
                def GestEvt3(evt):
                    return self.AnnulModifVal(evt)

                self.TabMat.TabMat.TabLabelNCol[C].bind('<Button-1>', GestEvt3)

        self.CanvasFrmFond.bind("<Button-1>", self.AnnulModifVal)
        self.CanvasMenu.CanvasMenu.bind("<Button-1>", self.AnnulModifVal)
        self.TabMat.TabMat.scrollable_canvas.interior.bind("<Button-1>", self.AnnulModifVal)
        self.TabMat.TabMat.scrollable_canvas.bind("<Button-1>", self.AnnulModifVal)

        self.MenuClicDroit = []
        for l in range(self.TabMat.TabMat.NLine):
            self.MenuClicDroit.append(tk.Menu(self.TabMat.TabMat.TabLabels[l][0], tearoff=0))

            def GestEvt5(evt, L=l):
                return self.AffichMenuClicDroit(evt, self.MenuClicDroit, L)

            self.TabMat.TabMat.TabLabels[l][0].bind('<Button-3>', GestEvt5)

        for i in range(len(self.MenuClicDroit)):
            self.MenuClicDroit[i].add_command(label="Voir le produit", command=self.VoirMat)
            self.MenuClicDroit[i].add_separator()
            self.MenuClicDroit[i].add_command(label="Modifier le produit", command=self.ModifMat)

        if self.CanvasBtnRetour is not None:
            self.CanvasBtnRetour.destroy()
            self.CanvasBtnRetour = None

    def AffichMenuClicDroit(self, event, MenuClicDroit, j):
        MenuClicDroit[j].post(event.x_root, event.y_root)
        self.NMatSelect = j

    def ModifVal(self, _, i, j):
        if j != 0 and ((self.MainAppli.BaseEnCours == "CHIMIE" and j != 11) or
                       (self.MainAppli.BaseEnCours == "PHYS" and j != 7)) and self.EntryManuelVal is None:
            if self.TriPar:
                index = 2
            else:
                index = 3
            self.EntryManuelVal = tk.Entry(self.TabMat.TabMat.scrollable_canvas.interior, text='',
                                           width=int(int(self.CanvasMenu.CanvasMenu['width']) *
                                                     self.ParaTabMat[index][j]),
                                           font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                           justify='right')
            self.EntryManuelVal.grid(row=i + 1, column=j)
            self.EntryManuelVal.insert(0, self.TabMat.TabMat.TabLabels[i][j]['text'])
            self.EntryManuelVal.focus_set()

            def GestEvt(evt):
                return self.ValidModifVal(evt, i, j)

            self.EntryManuelVal.bind('<Return>', GestEvt)
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def AnnulModifVal(self, _):
        if self.EntryManuelVal is not None:
            self.EntryManuelVal.grid_forget()
            self.EntryManuelVal = None
        self.TabMat.TabMat.ActionUnSelect()

    def ValidModifVal(self, _, i, j):
        OldVal = self.TabMat.TabMat.TabLabels[i][j]['text']
        if self.EntryManuelVal.get() != '':
            self.TabMat.TabMat.TabLabels[i][j]['text'] = self.EntryManuelVal.get()
            Qstock = 0
            if j == 2 or j == 4 or j == 6 or j == 8 or j == 10 or j == 12:
                try:
                    int(self.EntryManuelVal.get())
                    if self.MainAppli.BaseEnCours == "CHIMIE":
                        if j != 12 and (not self.TriPar or (self.TriPar and
                                                            self.StringTri.get() != 'Lieux de stockage')):
                            for n in range(2, 11, 2):
                                if self.TabMat.TabMat.TabLabels[i][n]['text'] != '':
                                    Qstock = Qstock + int(self.TabMat.TabMat.TabLabels[i][n]['text'])
                            self.TabMat.TabMat.TabLabels[i][11]['text'] = str(Qstock)
                    elif self.MainAppli.BaseEnCours == "PHYS":
                        if j != 8 and (not self.TriPar or (self.TriPar and
                                                           self.StringTri.get() != 'Lieux de stockage')):
                            for n in range(2, 7, 2):
                                if self.TabMat.TabMat.TabLabels[i][n]['text'] != '':
                                    Qstock = Qstock + int(self.TabMat.TabMat.TabLabels[i][n]['text'])
                            self.TabMat.TabMat.TabLabels[i][7]['text'] = str(Qstock)
                except:
                    self.EntryManuelVal.delete(0, tk.END)
                    self.EntryManuelVal.insert(0, OldVal)
                    self.TabMat.TabMat.TabLabels[i][j]['text'] = OldVal

            if self.EntryManuelVal.get() != OldVal:
                if self.CanvasBtnRetour is None:
                    self.ImgBtnRetour, wsize, hsize, self.CanvasBtnRetour, self.ImgCanvasBtnRetour = CanInWindow(
                        'Media/FrmMain/BtnRetour/', self.RatioX, self.RatioX, self.CanvasFrmFond, tk.CENTER,
                        int(self.SX * 0.94), int(self.SY * 0.045), 1)
                    self.CanvasBtnRetour.bind('<ButtonPress-1>', self.ActionBtnAnnulPress)
                    self.CanvasBtnRetour.bind('<ButtonRelease-1>', self.ActionAnnul)
                    ChangeCursor(self.CanvasBtnRetour)
                self.ListModif.append([i, j, OldVal])
                self.SaveModifVal(i, j)

            self.EntryManuelVal.grid_forget()
            self.EntryManuelVal = None

        else:
            self.EntryManuelVal.insert(0, OldVal)

    def SaveModifVal(self, i, j):
        if self.MainAppli.BaseEnCours == "CHIMIE":
            if not self.TriPar or (self.TriPar and self.StringTri.get() != 'Lieux de stockage'):
                REQUETE = ['LABOLIEU', 'LABOQUANT', 'LABOLIEU2', 'LABOQUANT2', 'SALLETPLIEU', 'SALLETPQUANT',
                           'POSTETPLIEU', 'POSTETPQUANT', 'SPECTROLIEU', 'SPECTROQUANT', 'QSTOCK', 'QUTIL']
                self.MainAppli.cur.execute("UPDATE MATERIEL SET '" + REQUETE[j - 1] + "' ='" +
                                           self.TabMat.TabMat.TabLabels[i][j]['text']
                                           + "' WHERE NOMS=\"" + self.TabMat.TabMat.TabLabels[i][0]['text'] + "\"")
                if j == 2 or j == 4 or j == 6 or j == 8 or j == 10:
                    self.MainAppli.cur.execute("UPDATE MATERIEL SET '" + REQUETE[10] + "' ='" +
                                               self.TabMat.TabMat.TabLabels[i][11]['text']
                                               + "' WHERE NOMS=\"" + self.TabMat.TabMat.TabLabels[i][0]['text'] + "\"")

                self.MainAppli.DataBaseChimie.commit()
                self.MainAppli.SaveListModifDTB('Chimie', 'Mise à jour données Matériel - ' +
                                                self.TabMat.TabMat.TabLabels[i][0]['text'])
            else:
                if j == 1:
                    self.MainAppli.cur.execute("UPDATE MATERIEL SET '" + "CATEGORIE" + "' ='" +
                                               self.TabMat.TabMat.TabLabels[i][1]['text']
                                               + "' WHERE NOMS=\"" + self.TabMat.TabMat.TabLabels[i][0]['text'] + "\"")
                    self.MainAppli.DataBaseChimie.commit()
                    self.MainAppli.SaveListModifDTB('Chimie', 'Mise à jour données Matériel - ' +
                                                    self.TabMat.TabMat.TabLabels[i][0]['text'])
                else:
                    self.MainAppli.cur.execute("SELECT " + "NOMS" + " FROM MATERIEL WHERE " + self.Salle + " = \"" +
                                               self.Lieu + "\" order by NOMS")
                    ListMatLieu = self.MainAppli.cur.fetchall()
                    ListNomMatLieu = []
                    for n in range(len(ListMatLieu)):
                        ListNomMatLieu.append(ListMatLieu[n][0])

                    if self.TabMat.TabMat.TabLabels[i][0]['text'] in ListNomMatLieu:
                        self.MainAppli.cur.execute("UPDATE MATERIEL SET '" + self.Quant + "' ='" +
                                                   self.TabMat.TabMat.TabLabels[i][j]['text']
                                                   + "' WHERE NOMS=\"" + self.TabMat.TabMat.TabLabels[i][0][
                                                       'text'] + "\"")
                    else:
                        self.MainAppli.cur.execute("UPDATE MATERIEL SET '" + self.Quant2 + "' ='" +
                                                   self.TabMat.TabMat.TabLabels[i][j]['text']
                                                   + "' WHERE NOMS=\"" + self.TabMat.TabMat.TabLabels[i][0][
                                                       'text'] + "\"")
                    self.MainAppli.DataBaseChimie.commit()
                    self.MainAppli.SaveListModifDTB('Chimie', 'Mise à jour données Matériel - ' +
                                                    self.TabMat.TabMat.TabLabels[i][0]['text'])
                    self.MainAppli.cur.execute("SELECT " + "LABOQUANT, LABOQUANT2, SALLETPQUANT, POSTETPQUANT, "
                                                           "SPECTROQUANT" + " FROM MATERIEL WHERE NOMS=\"" +
                                               self.TabMat.TabMat.TabLabels[i][0]['text'] + "\"")
                    ListMatQuant = self.MainAppli.cur.fetchall()
                    Qstock = 0
                    for n in range(5):
                        if ListMatQuant[0][n] != '':
                            Qstock = Qstock + int(ListMatQuant[0][n])
                    self.MainAppli.cur.execute("UPDATE MATERIEL SET '" + "QSTOCK" + "' ='" + str(Qstock)
                                               + "' WHERE NOMS=\"" + self.TabMat.TabMat.TabLabels[i][0]['text'] + "\"")
                    self.MainAppli.DataBaseChimie.commit()
                    self.MainAppli.SaveListModifDTB('Chimie', 'Mise à jour données Matériel - ' +
                                                    self.TabMat.TabMat.TabLabels[i][0]['text'])

        elif self.MainAppli.BaseEnCours == "PHYS":
            if not self.TriPar or (self.TriPar and self.StringTri.get() != 'Lieux de stockage'):
                REQUETE = ['LABOLIEU', 'LABOQUANT', 'SALLETPLIEU', 'SALLETPQUANT', 'RESLIEU', 'RESQUANT', 'QUTIL']
                self.MainAppli.curphys.execute("UPDATE MATERIEL SET '" + REQUETE[j - 1] + "' ='" +
                                               self.TabMat.TabMat.TabLabels[i][j]['text']
                                               + "' WHERE NOMS=\"" + self.TabMat.TabMat.TabLabels[i][0]['text'] + "\"")
                self.MainAppli.DataBasePhys.commit()
                self.MainAppli.SaveListModifDTB('Physique', 'Mise à jour données Matériel - ' +
                                                self.TabMat.TabMat.TabLabels[i][0]['text'])
            else:
                if j == 1:
                    self.MainAppli.curphys.execute("UPDATE MATERIEL SET '" + "CATEGORIE" + "' ='" +
                                                   self.TabMat.TabMat.TabLabels[i][1]['text']
                                                   + "' WHERE NOMS=\"" + self.TabMat.TabMat.TabLabels[i][0]['text'] +
                                                   "\"")
                else:
                    self.MainAppli.curphys.execute("UPDATE MATERIEL SET '" + self.Quant + "' ='" +
                                                   self.TabMat.TabMat.TabLabels[i][j]['text']
                                                   + "' WHERE NOMS=\"" + self.TabMat.TabMat.TabLabels[i][0][
                                                       'text'] + "\"")
                self.MainAppli.DataBasePhys.commit()
                self.MainAppli.SaveListModifDTB('Physique', 'Mise à jour données Matériel - ' +
                                                self.TabMat.TabMat.TabLabels[i][0]['text'])

    def ActionBtnAnnulPress(self, _):
        self.CanvasBtnRetour.itemconfig(self.ImgCanvasBtnRetour, image=self.ImgBtnRetour[2])

    def ActionAnnul(self, _):
        self.CanvasBtnRetour.itemconfig(self.ImgCanvasBtnRetour, image=self.ImgBtnRetour[1])
        self.TabMat.TabMat.TabLabels[self.ListModif[-1][0]][self.ListModif[-1][1]]['text'] = self.ListModif[-1][2]
        Qstock = 0
        if self.MainAppli.BaseEnCours == "CHIMIE":
            nfin = 11
        else:
            nfin = 7
        if self.ListModif[-1][1] == 2 or self.ListModif[-1][1] == 4 or self.ListModif[-1][1] == 6 or \
                self.ListModif[-1][1] == 8 or self.ListModif[-1][1] == 10:
            for n in range(2, nfin, 2):
                if self.TabMat.TabMat.TabLabels[self.ListModif[-1][0]][n]['text'] != '':
                    Qstock = Qstock + int(self.TabMat.TabMat.TabLabels[self.ListModif[-1][0]][n]['text'])
            self.TabMat.TabMat.TabLabels[self.ListModif[-1][0]][nfin]['text'] = str(Qstock)

        self.SaveModifVal(self.ListModif[-1][0], self.ListModif[-1][1])
        del self.ListModif[-1]
        if len(self.ListModif) == 0:
            self.CanvasBtnRetour.destroy()
            self.CanvasBtnRetour = None

    def VoirMat(self):
        self.MainAppli.IndexElt = self.MainAppli.ListNomProd.index(
            self.TabMat.TabMat.TabLabels[self.NMatSelect][0]['text'])
        self.ActionVoirMat()

    def ModifMat(self):
        self.MainAppli.IndexElt = self.MainAppli.ListNomProd.index(
            self.TabMat.TabMat.TabLabels[self.NMatSelect][0]['text'])
        self.ActionModifMat()

    def ActionVoirMat(self):
        self.destroy()
        self.MainAppli.NAction = 2
        self.MainAppli.ListBoxProduits.selection_clear(0, tk.END)
        self.MainAppli.ListBoxProduits.selection_set(self.MainAppli.IndexElt)
        self.MainAppli.ListBoxProduits.see(self.MainAppli.IndexElt)
        self.MainAppli.SelectProd()
        self.MainAppli.FrmLift()

    def ActionModifMat(self):
        self.ActionVoirMat()
        self.MainAppli.ActionV(3)

    def ActionIndexMat(self, _, L):
        self.MainAppli.IndexElt = self.MainAppli.ListNomProd.index(self.TabMat.TabMat.TabLabels[L][0]['text'])
        self.ActionVoirMat()

    def ClosePDF(self):
        self.MainAppli.parent.focus_force()
        self.MainAppli.FrmLift()
        self.focus_force()

    def MoveOnCanvas(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.CanvasBtnQuit.itemconfig(self.MainAppli.ImgCanvasBtnQuit, image=self.MainAppli.ImgBtnQuit[0])

    def CacheFrmTabRecapMat(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.ListBtnActionV[5].CanvasBtn.itemconfig(self.MainAppli.ListBtnActionV[5].ImgCanvasBtn,
                                                              image=self.MainAppli.ListBtnActionV[5].ImgBtn[2])
        self.destroy()
        self.MainAppli.Action2()
        self.MainAppli.parent.lift()
        self.MainAppli.FrmLift()
