from AppliDef import *


def ChercheMat(cur, ListChamp, Nom):
    ListMats = []
    try:
        cur.execute("SELECT " + ListChamp + " FROM MATERIEL WHERE NOMS = '" + Nom + "' order by NOMS")
        ListMats = cur.fetchall()
    except:
        cur.execute('SELECT ' + ListChamp + ' FROM MATERIEL WHERE NOMS = \"%' + Nom + '%\" order by NOMS')
        ListMats = cur.fetchall()
    finally:
        if len(ListMats) == 0:
            cur.execute('SELECT ' + ListChamp + ' FROM MATERIEL WHERE NOMS LIKE \"%' + Nom + '%\" order by NOMS')
            ListMats = cur.fetchall()
    return ListMats


class FrmMatHS(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.ListMatHS = []
        self.TabMatHS = None
        self.StringClasse = None
        self.ClasseListe = []
        self.ListClasse = None
        self.FrmAjoutMatHS = None
        self.MenuClicDroitTabMatHS = []
        self.LineSelect = 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.CacheFrmMatHS)

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond,
                                      'Récapitulatif annuel des matériels HS et des consommables', '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)

        LabelInCanvas(self.CanvasFrmFond, 'Année scolaire: ', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0), int(self.SX * 0.9),
                      int(self.SY * coefY), tk.NE)

        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("SELECT Annee FROM MatChimHS order by Materiel")
            self.ListAnnee = self.MainAppli.cur.fetchall()
        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("SELECT Annee FROM MatPhysHS order by Materiel")
            self.ListAnnee = self.MainAppli.curphys.fetchall()

        self.AnScolListe = []
        for i in range(len(self.ListAnnee)):
            if self.ListAnnee[i][0] not in self.AnScolListe:
                self.AnScolListe.append(self.ListAnnee[i][0])
        if self.MainAppli.AnScol not in self.AnScolListe:
            self.AnScolListe.append(self.MainAppli.AnScol)
        self.AnScolListe.sort()
        self.AnScol = tk.StringVar()
        self.AnScol.set(self.MainAppli.AnScol)
        self.ListAnScol = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.01), textvariable=self.AnScol,
                                          values=self.AnScolListe)
        self.CanvasFrmFond.create_window(int(self.SX * 0.9), int(self.SY * coefY), anchor=tk.NW,
                                         window=self.ListAnScol)
        self.ListAnScol.bind('<<ComboboxSelected>>', self.ActionAffichTabMatHS)

        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)

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

        self.TriListe = ['Matériel & Classe', 'Matériel', 'Classe']
        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.9), int(self.SY * 0.035), anchor=tk.NW,
                                         window=self.ListTri)
        self.ListTri.bind('<<ComboboxSelected>>', self.ActionAffichTabMatHS)
        self.AffichTabMatHS()

        self.BtnPlus = BtnAction(self.CanvasFrmFond, int(self.SX * 0.985), int(self.SY * 0.044), self.RatioX * 0.52,
                                 self.RatioX * 0.52, 'Media/FrmConsomProd/BtnPlus/')
        self.BtnPlus.CanvasBtn.bind('<ButtonRelease-1>', self.AjoutMatHS)

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

        self.CanvasFrmFond.pack()

    def ActionAffichTabMatHS(self, _):
        self.AffichTabMatHS()

    def AffichTabMatHS(self):
        self.EffaceMenu()
        LabelInCanvas(self.CanvasMenu.CanvasMenu, 'Matériel HS et consommables - ' + self.AnScol.get(), '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004), tk.NW)
        if self.StringTri.get() == 'Matériel & Classe':
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.MainAppli.cur.execute("SELECT " + "Materiel, Classe , Quant" +
                                           " FROM MatChimHS WHERE Annee = \"" + self.AnScol.get()
                                           + "\" order by Materiel")
                self.ListMatHS = self.MainAppli.cur.fetchall()
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.MainAppli.curphys.execute("SELECT " + "Materiel, Classe , Quant" +
                                               " FROM MatPhysHS WHERE Annee = \"" + self.AnScol.get()
                                               + "\" order by Materiel")
                self.ListMatHS = self.MainAppli.curphys.fetchall()
            listMatHS = []
            Index = 0
            for i in range(len(self.ListMatHS)):
                MatHSPresent = False
                for j in range(len(listMatHS)):
                    if self.ListMatHS[i][0] in listMatHS[j]:
                        MatHSPresent = True
                        Index = j
                if not MatHSPresent:
                    listMatHS.append([self.ListMatHS[i][0], self.ListMatHS[i][1], self.ListMatHS[i][2]])
                else:
                    listMatHS[Index][2] = str(int(self.ListMatHS[i][2]) + int(listMatHS[Index][2]))
            self.TabMatHS = Tableau(self.CanvasMenu.CanvasMenu, len(listMatHS), 3,
                                    ['Materiel', 'Classe', 'Quantité'], [0.065, 0.02, 0.02],
                                    AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                    AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)
            self.ListMatHS = []
            for i in range(len(listMatHS)):
                for j in range(3):
                    self.TabMatHS.TabLabels[i][j]['text'] = listMatHS[i][j]
                self.ListMatHS.append(listMatHS[i])
            self.InitMenuClicDroit()

        elif self.StringTri.get() == 'Matériel':
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.MainAppli.cur.execute("SELECT " + "Materiel, Quant" +
                                           " FROM MatChimHS WHERE Annee = \"" + self.AnScol.get()
                                           + "\" order by Materiel")
                self.ListMatHS = self.MainAppli.cur.fetchall()
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.MainAppli.curphys.execute("SELECT " + "Materiel, Quant" +
                                               " FROM MatPhysHS WHERE Annee = \"" + self.AnScol.get()
                                               + "\" order by Materiel")
                self.ListMatHS = self.MainAppli.curphys.fetchall()
            listMatHS = []
            Index = 0
            for i in range(len(self.ListMatHS)):
                MatHSPresent = False
                for j in range(len(listMatHS)):
                    if self.ListMatHS[i][0] in listMatHS[j]:
                        MatHSPresent = True
                        Index = j
                if not MatHSPresent:
                    listMatHS.append([self.ListMatHS[i][0], self.ListMatHS[i][1]])
                else:
                    listMatHS[Index][1] = str(int(self.ListMatHS[i][1]) + int(listMatHS[Index][1]))
            self.TabMatHS = Tableau(self.CanvasMenu.CanvasMenu, len(listMatHS), 3,
                                    ['Materiel', 'Quantité', 'Quantité en stock'], [0.065, 0.02, 0.015],
                                    AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                    AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)
            self.ListMatHS = []
            for i in range(len(listMatHS)):
                for j in range(2):
                    self.TabMatHS.TabLabels[i][j]['text'] = listMatHS[i][j]
                if self.MainAppli.BaseEnCours == "CHIMIE":
                    LMat = ChercheMat(self.MainAppli.cur, self.MainAppli.ListChampsTabMat, listMatHS[i][0])
                    if len(LMat) > 0:
                        self.TabMatHS.TabLabels[i][2]['text'] = LMat[0][13]
                elif self.MainAppli.BaseEnCours == "PHYS":
                    LMat = ChercheMat(self.MainAppli.curphys, self.MainAppli.ListChampsTabMatPhys, listMatHS[i][0])
                    if len(LMat) > 0:
                        QuantTot = ''
                        if LMat[0][4] is not None and LMat[0][4] != '':
                            QuantTot = LMat[0][4]
                        if LMat[0][6] is not None and LMat[0][6] != '':
                            if QuantTot != '':
                                QuantTot = str(int(QuantTot) + int(LMat[0][6]))
                            else:
                                QuantTot = LMat[0][6]
                        if LMat[0][8] is not None and LMat[0][8] != '':
                            if QuantTot != '':
                                QuantTot = str(int(QuantTot) + int(LMat[0][8]))
                            else:
                                QuantTot = LMat[0][8]
                        self.TabMatHS.TabLabels[i][2]['text'] = QuantTot
                self.ListMatHS.append(listMatHS[i])
            self.UpdateQUtil(listMatHS)
            self.InitMenuClicDroit()

        elif self.StringTri.get() == 'Classe':
            LabelInCanvas(self.CanvasMenu.CanvasMenu, 'Classe: ',
                          '#E0E0E0',
                          AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                          int(int(self.CanvasMenu.CanvasMenu['width']) * 0.165),
                          int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004), tk.NW)
            self.ClasseListe = self.MainAppli.ListClasses
            self.StringClasse = tk.StringVar()
            self.StringClasse.set(self.ClasseListe[0])
            self.ListClasse = ListeDeroulante(self.CanvasMenu.CanvasMenu,
                                              int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01),
                                              textvariable=self.StringClasse,
                                              values=self.ClasseListe)
            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.ListClasse)
            self.ListClasse.bind('<<ComboboxSelected>>', self.ActionTriMatHSByClass)
            self.TriMatHSByClass()

    def ActionTriMatHSByClass(self, _):
        self.TriMatHSByClass()

    def TriMatHSByClass(self):
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("SELECT " + "Materiel, Quant" +
                                       " FROM MatChimHS WHERE Annee = \"" + self.AnScol.get() +
                                       "\" and Classe = \"" + self.StringClasse.get() + "\" order by Materiel")
            self.ListMatHS = self.MainAppli.cur.fetchall()
        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("SELECT " + "Materiel, Quant" +
                                           " FROM MatPhysHS WHERE Annee = \"" + self.AnScol.get() +
                                           "\" and Classe = \"" + self.StringClasse.get() + "\" order by Materiel")
            self.ListMatHS = self.MainAppli.curphys.fetchall()

        listMatHS = []
        Index = 0
        for i in range(len(self.ListMatHS)):
            MatHSPresent = False
            for j in range(len(listMatHS)):
                if self.ListMatHS[i][0] in listMatHS[j]:
                    MatHSPresent = True
                    Index = j
            if not MatHSPresent:
                listMatHS.append([self.ListMatHS[i][0], self.ListMatHS[i][1]])
            else:
                listMatHS[Index][1] = str(int(self.ListMatHS[i][1]) + int(listMatHS[Index][1]))

        self.TabMatHS = Tableau(self.CanvasMenu.CanvasMenu, len(listMatHS), 2,
                                ['Matériel', 'Quantité'], [0.065, 0.02],
                                AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)
        self.ListMatHS = []
        for i in range(len(listMatHS)):
            for j in range(2):
                self.TabMatHS.TabLabels[i][j]['text'] = listMatHS[i][j]
            self.ListMatHS.append(listMatHS[i])
        self.InitMenuClicDroit()

    def AjoutMatHS(self, _):
        self.FrmAjoutMatHS = FrmAjoutMatHS(self.MainAppli.CanvasFrmMain, self.RatioX, self.RatioY, self)

    def UpdateQUtil(self, ListMat):
        if self.MainAppli.BaseEnCours == "CHIMIE":
            Index = 14
            cur = self.MainAppli.cur
            champ = self.MainAppli.ListChampsTabMat
        else:
            Index = 9
            cur = self.MainAppli.curphys
            champ = self.MainAppli.ListChampsTabMatPhys
        for i in range(len(ListMat)):
            MAJ = False
            LMat = ChercheMat(cur, champ, ListMat[i][0])
            if LMat[0][2] == 'Consommables':
                if LMat[0][Index] is not None and LMat[0][Index] != '':
                    if int(ListMat[i][1]) > int(LMat[0][Index]):
                        MAJ = True
                else:
                    MAJ = True
                if MAJ:
                    Rep = tkMB.askyesno('Mise à jour des consommations annuelles des "consommables"',
                                        'La quantité consommée annuelle de "' +
                                        ListMat[i][0] + '" est supérieure à celle enregistrée. '
                                                        'Voulez-vous mettre à jour les données?', parent=self)
                    if Rep:
                        if self.MainAppli.BaseEnCours == "CHIMIE":
                            self.MainAppli.cur.execute(
                                "UPDATE MATERIEL SET QUTIL ='" + ListMat[i][1] + "' WHERE " + 'NOMS="' + LMat[0][0] +
                                '"')
                            self.MainAppli.DataBaseChimie.commit()
                            self.MainAppli.SaveListModifDTB('Chimie',
                                                            'Mise à jour - Consommation annuelle matériel - '
                                                            + LMat[0][0])
                        elif self.MainAppli.BaseEnCours == "PHYS":
                            self.MainAppli.curphys.execute(
                                "UPDATE MATERIEL SET QUTIL ='" + ListMat[i][1] + "' WHERE " + 'NOMS="' + LMat[0][0] +
                                '"')
                            self.MainAppli.DataBasePhys.commit()
                            self.MainAppli.SaveListModifDTB('Physique',
                                                            'Mise à jour - Consommation annuelle matériel - '
                                                            + LMat[0][0])

    def InitMenuClicDroit(self):
        self.MenuClicDroitTabMatHS = []
        for i in range(len(self.ListMatHS)):
            self.MenuClicDroitTabMatHS.append(tk.Menu(self.TabMatHS.TabLabels[i][0], tearoff=0))
            self.MenuClicDroitTabMatHS[i].add_command(label='Commander le matériel', command=self.CommandMatCD)

            def GestEvt(evt, l=i):
                return self.CommandMat(evt, l)

            self.TabMatHS.TabLabels[i][0].bind('<Double-1>', GestEvt)

            def GestEvt2(evt, L=i):
                return self.AffichMenuClicDroit(evt, self.MenuClicDroitTabMatHS, L)

            self.TabMatHS.TabLabels[i][0].bind("<Button-3>", GestEvt2)

    def CommandMat(self, _, l):
        self.ActionCommandMat(l)

    def ActionCommandMat(self, N):
        self.destroy()
        self.MainAppli.NAction = 2
        self.MainAppli.ActionV(7)
        self.MainAppli.FrmCommandMat.ActionAjoutMatACom(0)
        self.MainAppli.FrmCommandMat.FrmAjoutMatACom.EntryMat.Data.set(self.ListMatHS[N][0])
        self.MainAppli.FrmCommandMat.FrmAjoutMatACom.ActionModifMat()

    def CommandMatCD(self):
        self.ActionCommandMat(self.LineSelect)

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

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

    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 CacheFrmMatHS(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.ListBtnActionV[6].CanvasBtn.itemconfig(self.MainAppli.ListBtnActionV[6].ImgCanvasBtn,
                                                              image=self.MainAppli.ListBtnActionV[6].ImgBtn[2])
        self.destroy()
        self.MainAppli.parent.lift()
        self.MainAppli.Action2()


class FrmAjoutMatHS(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.Classe = tk.StringVar()
        self.ClasseListe = self.MainAppli.MainAppli.ListClasses
        self.ListMatHS = []
        self.TabMatHS = None
        self.TitreClasse = None
        self.ListeClasse = None
        self.EntryMat = None
        self.ListBoxMat = None
        self.TitreQuant = None
        self.EntryQuant = None
        self.BtnOK = None
        self.BtnAnnul = None
        self.ListMats = []
        self.FrmMajStockMat = None

        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.MainAppli.Nconfig, 'YTitreFrm', self.MainAppli.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.CacheFrmAjoutMatHS)

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond, 'Ajouter du matériel HS ou des consommables', '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)

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

        self.CanvasMenu2 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.965), int(self.SX * 0.998), int(self.SY * 0.031), tk.NE)

        self.AffichMatHS()
        self.AffichSelectMat()

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

        self.CanvasFrmFond.pack()

    def AffichMatHS(self):
        self.EffaceCanvasMenu1()
        if self.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.MainAppli.cur.execute("SELECT " + "Materiel, Classe , Quant" +
                                                 " FROM MatChimHS WHERE Annee = \"" +
                                                 self.MainAppli.MainAppli.AnScol + "\" order by Materiel")
            self.ListMatHS = self.MainAppli.MainAppli.cur.fetchall()
        elif self.MainAppli.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.MainAppli.curphys.execute("SELECT " + "Materiel, Classe , Quant" +
                                                     " FROM MatPhysHS WHERE Annee = \"" +
                                                     self.MainAppli.MainAppli.AnScol + "\" order by Materiel")
            self.ListMatHS = self.MainAppli.MainAppli.curphys.fetchall()

        LabelInCanvas(self.CanvasMenu1.CanvasMenu, 'Matériel HS et consommables - ' + self.MainAppli.MainAppli.AnScol,
                      '#E0E0E0', AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.004), tk.NW)

        self.TabMatHS = Tableau(self.CanvasMenu1.CanvasMenu, len(self.ListMatHS), 3,
                                ['Matériel', 'Classe', 'Quantité'], [0.066, 0.02, 0.02],
                                AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0),
                                AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0), self)
        for i in range(len(self.ListMatHS)):
            for j in range(3):
                self.TabMatHS.TabLabels[i][j]['text'] = self.ListMatHS[i][j]

    def AffichSelectMat(self):
        Titre = ''
        if self.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
            Titre = "Sélection d'un matériel de chimie"
        elif self.MainAppli.MainAppli.BaseEnCours == "PHYS":
            Titre = "Sélection d'un matériel de Physique"
        LabelInCanvas(self.CanvasMenu2.CanvasMenu, Titre, '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.004), tk.NW)

        self.TitreClasse = self.CanvasMenu2.CanvasMenu.create_text(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.72),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.06), text='Classe :',
            font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 1, 'bold', 0), anchor=tk.W)

        self.Classe.set(self.ClasseListe[0])
        self.ListeClasse = ListeDeroulante(self.CanvasMenu2.CanvasMenu,
                                           int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.02),
                                           textvariable=self.Classe, values=self.ClasseListe)
        self.CanvasMenu2.CanvasMenu.create_window(int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.82),
                                                  int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.06),
                                                  anchor=tk.W,
                                                  window=self.ListeClasse)

        self.EntryMat = EntryData(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.108),
                                  int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                                  int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.12), tk.CENTER,
                                  AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 2, 'bold', 0))

        self.EntryMat.EntryData.config(justify='center')
        self.EntryMat.EntryData.bind('<KeyRelease>', self.ModifMat)

        self.ListBoxMat = Scrollable_ListBox(self.CanvasMenu2.CanvasMenu,
                                             int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                                             int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.15),
                                             int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.158),
                                             int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.042))

        self.ListBoxMat.ListBox.bind('<<ListboxSelect>>', self.OnSelectListBox)

        self.TitreQuant = self.CanvasMenu2.CanvasMenu.create_text(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.88), text='Sélection de la quantité',
            font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 1), anchor=tk.W)

        self.EntryQuant = EntryData(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.025),
                                    int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.05),
                                    int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.92), tk.W,
                                    AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 2, 'bold', 0))

        self.EntryQuant.EntryData.config(justify='center')
        self.EntryQuant.EntryData.bind('<KeyRelease>', self.ModifQuant)

        self.BtnOK = BtnAction(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.88),
                               int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.95), self.RatioX * 0.75,
                               self.RatioX * 0.75, 'Media/FrmAjout/BtnOK2/')
        self.BtnOK.CanvasBtn.bind('<ButtonRelease-1>', self.ValidAjoutMat)
        self.BtnAnnul = BtnAction(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.95),
                                  int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.95), self.RatioX * 0.75,
                                  self.RatioX * 0.75, 'Media/FrmAjout/BtnAnnul2/')
        self.BtnAnnul.CanvasBtn.bind('<ButtonRelease-1>', self.AnnulAjoutMat)

        self.InitSelectMat()

    def InitSelectMat(self):
        self.Classe.set(self.ClasseListe[0])
        self.EntryMat.Data.set('')
        self.EntryMat.EntryData.focus()
        self.EntryQuant.Data.set('')
        self.AffichListMat()

    def AffichListMat(self):
        if self.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.MainAppli.cur.execute("select " + self.MainAppli.MainAppli.ListChampsTabMat +
                                                 " from MATERIEL order by NOMS")
            self.ListMats = self.MainAppli.MainAppli.cur.fetchall()
        elif self.MainAppli.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.MainAppli.curphys.execute("select " + self.MainAppli.MainAppli.ListChampsTabMatPhys +
                                                     " from MATERIEL order by NOMS")
            self.ListMats = self.MainAppli.MainAppli.curphys.fetchall()
        self.ListBoxMat.ListBox.delete(0, tk.END)
        for i in range(len(self.ListMats)):
            self.ListBoxMat.ListBox.insert(tk.END, self.ListMats[i][0])
        self.ListBoxMat.ListBox.selection_set(0)
        if len(self.ListMats) > 0:
            self.EntryMat.Data.set(self.ListMats[0][0])

    def OnSelectListBox(self, evt):
        try:
            w = evt.widget
            IndexElt = int(w.curselection()[0])
            self.EntryMat.Data.set(self.ListMats[IndexElt][0])
        except:
            pass

    def ModifMat(self, _):
        if self.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.MainAppli.cur.execute('SELECT ' + self.MainAppli.MainAppli.ListChampsTabMat +
                                                 ' FROM MATERIEL WHERE NOMS LIKE \'%' +
                                                 self.EntryMat.Data.get() + '%\' order by NOMS')
            self.ListMats = self.MainAppli.MainAppli.cur.fetchall()
        elif self.MainAppli.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.MainAppli.curphys.execute('SELECT ' + self.MainAppli.MainAppli.ListChampsTabMatPhys +
                                                     ' FROM MATERIEL WHERE NOMS LIKE \'%' +
                                                     self.EntryMat.Data.get() + '%\' order by NOMS')
            self.ListMats = self.MainAppli.MainAppli.curphys.fetchall()

        self.ListBoxMat.ListBox.delete(0, tk.END)
        for i in range(len(self.ListMats)):
            self.ListBoxMat.ListBox.insert(tk.END, self.ListMats[i][0])
        self.ListBoxMat.ListBox.selection_set(0)

    def ModifQuant(self, _):
        try:
            int(self.EntryQuant.Data.get())
        except:
            self.EntryQuant.Data.set('')

    def ValidAjoutMat(self, _):
        self.BtnOK.CanvasBtn.itemconfig(self.BtnOK.ImgCanvasBtn, image=self.BtnOK.ImgBtn[0])
        if self.EntryMat.EntryData.get() != '' and self.EntryQuant.Data.get() != '':
            listMats = []
            if self.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
                listMats = self.ChercheMat(self.EntryMat.EntryData.get())
            elif self.MainAppli.MainAppli.BaseEnCours == "PHYS":
                listMats = self.ChercheMatPhys(self.EntryMat.EntryData.get())
            self.FrmMajStockMat = FrmMajStockMat(self.MainAppli.MainAppli.CanvasFrmMain, self.RatioX, self.RatioY,
                                                 self.MainAppli.MainAppli.SizeFont, listMats[0],
                                                 self.EntryQuant.Data.get(), self)
        else:
            tkMB.showwarning('Attention', "Veuillez choisir un matériel et indiquer la quantité !", parent=self)
            self.lift()

    def MajMatHS(self, Mat, Classe, Quant):
        ListMatHS = []
        if self.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.MainAppli.cur.execute("SELECT Quant FROM MatChimHS WHERE Annee ='"
                                                 + self.MainAppli.MainAppli.AnScol
                                                 + "' and " + 'Materiel = "' + Mat + "' and Classe ='" + Classe + '"')
            ListMatHS = self.MainAppli.MainAppli.cur.fetchall()
        elif self.MainAppli.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.MainAppli.curphys.execute("SELECT Quant FROM MatPhysHS WHERE Annee ='"
                                                     + self.MainAppli.MainAppli.AnScol + "' and " + 'Materiel = "' +
                                                     Mat + "' and Classe ='" + Classe + '"')
            ListMatHS = self.MainAppli.MainAppli.curphys.fetchall()

        if len(ListMatHS) > 0:
            QuantMatHS = str(Quant + int(ListMatHS[0][0]))
            if self.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
                self.MainAppli.MainAppli.cur.execute("UPDATE MatChimHS SET Quant ='" + QuantMatHS + "' WHERE Materiel='"
                                                     + Mat + "' and Annee ='" + self.MainAppli.MainAppli.AnScol
                                                     + "'and Classe ='" + Classe + "'")
            elif self.MainAppli.MainAppli.BaseEnCours == "PHYS":
                self.MainAppli.MainAppli.curphys.execute(
                    "UPDATE MatPhysHS SET Quant ='" + QuantMatHS + "' WHERE Materiel='"
                    + Mat + "' and Annee ='" + self.MainAppli.MainAppli.AnScol
                    + "'and Classe ='" + Classe + "'")
        else:
            QuantMatHS = str(Quant)
            data = [(self.MainAppli.MainAppli.AnScol, Mat, Classe, QuantMatHS)]
            if self.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
                self.MainAppli.MainAppli.cur.execute(
                    "INSERT INTO MatChimHS(Annee, Materiel, Classe , Quant) VALUES(?,?,?,?)", data[0])
            elif self.MainAppli.MainAppli.BaseEnCours == "PHYS":
                self.MainAppli.MainAppli.curphys.execute(
                    "INSERT INTO MatPhysHS(Annee, Materiel, Classe , Quant) VALUES(?,?,?,?)", data[0])

        if self.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.MainAppli.DataBaseChimie.commit()
            self.MainAppli.MainAppli.SaveListModifDTB('Chimie', 'Mise à jour - Matériel HS - ' + Mat)
        elif self.MainAppli.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.MainAppli.DataBasePhys.commit()
            self.MainAppli.MainAppli.SaveListModifDTB('Physique', 'Mise à jour - Matériel HS - ' + Mat)

    def ChercheMat(self, Nom):
        ListMats = []
        try:
            self.MainAppli.MainAppli.cur.execute("SELECT " + self.MainAppli.MainAppli.ListChampsTabMat +
                                                 " FROM MATERIEL WHERE NOMS = '" + Nom + "' order by NOMS")
            ListMats = self.MainAppli.MainAppli.cur.fetchall()
        except:
            self.MainAppli.MainAppli.cur.execute('SELECT ' + self.MainAppli.MainAppli.ListChampsTabMat +
                                                 ' FROM MATERIEL WHERE NOMS =\"%' + Nom + '%\" order by NOMS')
            ListMats = self.MainAppli.MainAppli.cur.fetchall()
        finally:
            if len(ListMats) == 0:
                self.MainAppli.MainAppli.cur.execute('SELECT ' + self.MainAppli.MainAppli.ListChampsTabMat +
                                                     ' FROM MATERIEL WHERE NOMS LIKE \"%' + Nom + '%\" order by NOMS')
                ListMats = self.MainAppli.MainAppli.cur.fetchall()
        return ListMats

    def ChercheMatPhys(self, Nom):
        ListMats = []
        try:
            self.MainAppli.MainAppli.curphys.execute("SELECT " + self.MainAppli.MainAppli.ListChampsTabMatPhys +
                                                     " FROM MATERIEL WHERE NOMS = '" + Nom + "' order by NOMS")
            ListMats = self.MainAppli.MainAppli.curphys.fetchall()
        except:
            self.MainAppli.MainAppli.curphys.execute('SELECT ' + self.MainAppli.MainAppli.ListChampsTabMatPhys +
                                                     ' FROM MATERIEL WHERE NOMS =\"%' + Nom + '%\" order by NOMS')
            ListMats = self.MainAppli.MainAppli.curphys.fetchall()
        finally:
            if len(ListMats) == 0:
                self.MainAppli.MainAppli.curphys.execute('SELECT ' + self.MainAppli.MainAppli.ListChampsTabMatPhys +
                                                         ' FROM MATERIEL WHERE NOMS LIKE \"%' + Nom
                                                         + '%\" order by NOMS')
                ListMats = self.MainAppli.MainAppli.curphys.fetchall()
        return ListMats

    def AnnulAjoutMat(self, _):
        self.CacheFrmAjoutMatHS(_)

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

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

    def CacheFrmAjoutMatHS(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.destroy()
        self.MainAppli.FrmAjoutMatHS = None
        self.MainAppli.MainAppli.FrmLift()
        self.MainAppli.lift()
        self.MainAppli.AffichTabMatHS()


class FrmMajStockMat(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, SizeFont, Mat, Quant, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.container = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.SizeFont = SizeFont
        self.EntryQuant = []
        self.QuantDeStock = None
        self.CanvasBoite = None
        self.ImgEtiqMat = []
        self.CanvasImgEtiqMat = None
        self.ImgCanvasImgEtiqMat = None
        self.QuantStock = None
        self.QuantInit = []
        self.QuantTot = 0
        self.QuantToDeStock = 0
        self.QuantToDeStockInit = 0
        self.QuantTotInit = 0
        self.Mat = []
        self.QuantParLieu = []
        self.ListLieu = []

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

        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.668)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.06)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        LabelInCanvas(self.CanvasFrmFond, 'Mise à jour du stock - ' + Mat[0], '#E0E0E0',
                      AppliFont('Helvetica', SizeFont, 'normal', 0), int(self.SX * 0.01),
                      int(self.SY * 0.004), tk.NW)

        self.BtnOK = BtnAction(self.CanvasFrmFond, int(self.SX * 0.83),
                               int(self.SY * 0.95), self.RatioX * 0.75,
                               self.RatioX * 0.75, 'Media/FrmAjout/BtnOK2/')
        self.BtnOK.CanvasBtn.bind('<ButtonRelease-1>', self.Valid)
        self.BtnAnnul = BtnAction(self.CanvasFrmFond, int(self.SX * 0.90),
                                  int(self.SY * 0.95), self.RatioX * 0.75,
                                  self.RatioX * 0.75, 'Media/FrmAjout/BtnAnnul2/')
        self.BtnAnnul.CanvasBtn.bind('<ButtonRelease-1>', self.Annul)

        if self.MainAppli.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
            self.AffichStockMatChim(Mat, Quant)
        elif self.MainAppli.MainAppli.MainAppli.BaseEnCours == "PHYS":
            self.AffichStockMatPhys(Mat, Quant)

        self.CanvasFrmFond.focus_set()
        self.CanvasFrmFond.pack()

    def AffichFondStockMat(self, Mat, Quant):
        self.EntryQuant = []
        self.QuantInit = []
        self.QuantToDeStock = int(Quant)
        self.QuantToDeStockInit = self.QuantToDeStock
        self.Mat = Mat
        self.ListLieu = []

        LabelInCanvas(self.CanvasFrmFond, Mat[0], '#E0E0E0',
                      AppliFont('Helvetica', self.SizeFont + 3, 'bold', 0),
                      int(self.SX * 0.5), int(self.SY * 0.08), tk.CENTER)

        self.CanvasFrmFond.create_text(int(self.SX * 0.05), int(self.SY * 0.15), text='Quantité à déstocker:',
                                       font=AppliFont('Helvetica', self.SizeFont + 2, 'bold', 1), anchor=tk.W)
        self.QuantDeStock = LabelInCanvas(self.CanvasFrmFond, Quant, '#C0C0C0',
                                          AppliFont('Helvetica', self.SizeFont + 5, 'bold', 0),
                                          int(self.SX * 0.4), int(self.SY * 0.15), tk.CENTER)

        self.CanvasBoite = CanvasInWindow('Media/FrmInfo/Boite/', self.RatioX * 1.3, self.RatioY * 1.3,
                                          self.CanvasFrmFond, tk.CENTER, int(self.SX * 0.5), int(self.SY * 0.5), 0)

        if Mat[2] is not None and Mat[2] != '':
            LabelInCanvas(self.CanvasBoite.CanvasListIma, Mat[2], '#C0C0C0',
                          AppliFont('Helvetica', self.SizeFont + 1, 'bold', 0),
                          int(self.CanvasBoite.wsize * 0.5), int(self.CanvasBoite.hsize * 0.1), tk.CENTER)
            if Mat[1] is not None and Mat[1] != '':
                self.ImgEtiqMat = []
                Path = ''
                if self.MainAppli.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
                    Path = 'Datas/VisuelMatChim/'
                elif self.MainAppli.MainAppli.MainAppli.BaseEnCours == "PHYS":
                    Path = 'Datas/VisuelMatPhys/'
                img = Image.open(Path + Mat[1])
                imgEtiqwsize = int(self.CanvasBoite.wsize * 0.295)
                imgEtiqhsize = int(imgEtiqwsize * float(img.size[1]) / float(img.size[0]))
                if imgEtiqhsize > self.CanvasBoite.hsize * 0.115:
                    imgEtiqhsize = int(self.CanvasBoite.hsize * 0.115)
                    imgEtiqwsize = int(imgEtiqhsize * float(img.size[0]) / float(img.size[1]))
                img = img.resize((imgEtiqwsize, imgEtiqhsize), Image.ANTIALIAS)
                self.ImgEtiqMat.append(ImageTk.PhotoImage(img))

                self.CanvasImgEtiqMat = CanvasApp(self.CanvasBoite.CanvasListIma, width=imgEtiqwsize,
                                                  height=imgEtiqhsize)
                self.CanvasBoite.CanvasListIma.create_window(int(self.CanvasBoite.wsize * 0.497),
                                                             int(self.CanvasBoite.hsize * 0.158), anchor=tk.N,
                                                             window=self.CanvasImgEtiqMat)
                self.ImgCanvasImgEtiqMat = self.CanvasImgEtiqMat.create_image(0, 0, anchor=tk.NW,
                                                                              image=self.ImgEtiqMat[0])
                CreateCadre(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.494 - imgEtiqwsize / 2),
                            int(self.CanvasBoite.hsize * 0.155),
                            int(self.CanvasBoite.wsize * 0.500 - imgEtiqwsize / 2) + imgEtiqwsize,
                            int(self.CanvasBoite.hsize * 0.161) + imgEtiqhsize)

            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.35), text='Lieu de stockage',
                font=AppliFont('Helvetica', self.SizeFont + 1, 'bold', 1), anchor=tk.CENTER)
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.35), text='Quantité',
                font=AppliFont('Helvetica', self.SizeFont + 1, 'bold', 1), anchor=tk.CENTER)

    def AffichStockMatPhys(self, Mat, Quant):
        self.AffichFondStockMat(Mat, Quant)

        LabelInCanvas(self.CanvasBoite.CanvasListIma, 'Laboratoire', '#C0C0C0',
                      AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                      int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.41), tk.CENTER)
        if Mat[3] is not None and Mat[3] != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.47), text=Mat[3],
                font=AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0), anchor=tk.CENTER, fill='blue')
            self.EntryQuant.append(EntryData(self.CanvasBoite.CanvasListIma,
                                             int(self.CanvasBoite.wsize * 0.01),
                                             int(self.CanvasBoite.wsize * 0.67),
                                             int(self.CanvasBoite.hsize * 0.47), tk.CENTER,
                                             AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0)))

            self.EntryQuant[-1].EntryData.config(justify='center')
            self.EntryQuant[-1].Data.set(Mat[4])
            self.QuantInit.append(Mat[4])
            self.ListLieu.append("LaboQuant")

        LabelInCanvas(self.CanvasBoite.CanvasListIma, 'Salle TP', '#C0C0C0',
                      AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                      int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.58), tk.CENTER)

        if Mat[5] is not None and Mat[5] != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.64), text=Mat[5],
                font=AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0), anchor=tk.CENTER, fill='blue')
            self.EntryQuant.append(EntryData(self.CanvasBoite.CanvasListIma,
                                             int(self.CanvasBoite.wsize * 0.01),
                                             int(self.CanvasBoite.wsize * 0.67),
                                             int(self.CanvasBoite.hsize * 0.64), tk.CENTER,
                                             AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0)))

            self.EntryQuant[-1].EntryData.config(justify='center')
            self.EntryQuant[-1].Data.set(Mat[6])
            self.QuantInit.append(Mat[6])
            self.ListLieu.append("SalleTPQuant")

        LabelInCanvas(self.CanvasBoite.CanvasListIma, 'Réserve', '#C0C0C0',
                      AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                      int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.75), tk.CENTER)

        if Mat[7] is not None and Mat[7] != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.81), text=Mat[7],
                font=AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0), anchor=tk.CENTER, fill='blue')
            self.EntryQuant.append(EntryData(self.CanvasBoite.CanvasListIma,
                                             int(self.CanvasBoite.wsize * 0.01),
                                             int(self.CanvasBoite.wsize * 0.67),
                                             int(self.CanvasBoite.hsize * 0.81), tk.CENTER,
                                             AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0)))

            self.EntryQuant[-1].EntryData.config(justify='center')
            self.EntryQuant[-1].Data.set(Mat[8])
            self.QuantInit.append(Mat[8])
            self.ListLieu.append("ResQuant")

        self.QuantParLieu = [i for i in self.QuantInit]
        self.QuantTot = 0
        for i in range(len(self.QuantParLieu)):
            self.QuantTot = self.QuantTot + int(self.QuantParLieu[i])
        self.QuantTotInit = self.QuantTot
        QuantMin = ''
        if Mat[9] is not None and Mat[9] != '':
            QuantMin = Mat[9]
        self.CanvasBoite.CanvasListIma.create_text(
            int(self.CanvasBoite.wsize * 0.18), int(self.CanvasBoite.hsize * 0.88), text='Stock - Quantité totale: ',
            font=AppliFont('Helvetica', self.SizeFont + 1, 'bold', 0), anchor=tk.W)

        self.QuantStock = LabelInCanvas(self.CanvasBoite.CanvasListIma, str(self.QuantTot), '#C0C0C0',
                                        AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0),
                                        int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.88),
                                        tk.CENTER)
        if QuantMin != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.18), int(self.CanvasBoite.hsize * 0.92),
                text='Stock - Quantité minimale: ',
                font=AppliFont('Helvetica', self.SizeFont, 'bold', 0), anchor=tk.W)
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.92), text=QuantMin,
                font=AppliFont('Helvetica', self.SizeFont, 'bold', 0), anchor=tk.CENTER, fill='blue')

        for i in range(len(self.EntryQuant)):
            def GestEvt(evt, j=i):
                return self.ModifQuant(evt, j)

            self.EntryQuant[i].EntryData.bind('<KeyRelease>', GestEvt)

    def AffichStockMatChim(self, Mat, Quant):
        self.AffichFondStockMat(Mat, Quant)

        LabelInCanvas(self.CanvasBoite.CanvasListIma, 'Laboratoire', '#C0C0C0',
                      AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                      int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.41), tk.CENTER)
        if Mat[3] is not None and Mat[3] != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.47), text=Mat[3],
                font=AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0), anchor=tk.CENTER, fill='blue')
            self.EntryQuant.append(EntryData(self.CanvasBoite.CanvasListIma,
                                             int(self.CanvasBoite.wsize * 0.01),
                                             int(self.CanvasBoite.wsize * 0.67),
                                             int(self.CanvasBoite.hsize * 0.47), tk.CENTER,
                                             AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0)))

            self.EntryQuant[-1].EntryData.config(justify='center')
            self.EntryQuant[-1].Data.set(Mat[4])
            self.QuantInit.append(Mat[4])
            self.ListLieu.append("LABOQUANT")

        if Mat[5] is not None and Mat[5] != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.51), text=Mat[5],
                font=AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0), anchor=tk.CENTER, fill='blue')
            self.EntryQuant.append(EntryData(self.CanvasBoite.CanvasListIma,
                                             int(self.CanvasBoite.wsize * 0.01),
                                             int(self.CanvasBoite.wsize * 0.67),
                                             int(self.CanvasBoite.hsize * 0.51), tk.CENTER,
                                             AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0)))
            self.EntryQuant[-1].EntryData.config(justify='center')
            self.EntryQuant[-1].Data.set(Mat[6])
            self.QuantInit.append(Mat[6])
            self.ListLieu.append("LABOQUANT2")

        LabelInCanvas(self.CanvasBoite.CanvasListIma, 'Salle TP', '#C0C0C0',
                      AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                      int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.58), tk.CENTER)

        if Mat[7] is not None and Mat[7] != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.64), text=Mat[7],
                font=AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0), anchor=tk.CENTER, fill='blue')
            self.EntryQuant.append(EntryData(self.CanvasBoite.CanvasListIma,
                                             int(self.CanvasBoite.wsize * 0.01),
                                             int(self.CanvasBoite.wsize * 0.67),
                                             int(self.CanvasBoite.hsize * 0.64), tk.CENTER,
                                             AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0)))

            self.EntryQuant[-1].EntryData.config(justify='center')
            self.EntryQuant[-1].Data.set(Mat[8])
            self.QuantInit.append(Mat[8])
            self.ListLieu.append("SALLETPQUANT")

        if Mat[9] is not None and Mat[9] != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.68), text=Mat[9],
                font=AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0), anchor=tk.CENTER, fill='blue')
            self.EntryQuant.append(EntryData(self.CanvasBoite.CanvasListIma,
                                             int(self.CanvasBoite.wsize * 0.01),
                                             int(self.CanvasBoite.wsize * 0.67),
                                             int(self.CanvasBoite.hsize * 0.68), tk.CENTER,
                                             AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0)))

            self.EntryQuant[-1].EntryData.config(justify='center')
            self.EntryQuant[-1].Data.set(Mat[10])
            self.QuantInit.append(Mat[10])
            self.ListLieu.append("POSTETPQUANT")

        LabelInCanvas(self.CanvasBoite.CanvasListIma, 'Salle spectroscopie', '#C0C0C0',
                      AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                      int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.75), tk.CENTER)

        if Mat[11] is not None and Mat[11] != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.81), text=Mat[11],
                font=AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0), anchor=tk.CENTER, fill='blue')
            self.EntryQuant.append(EntryData(self.CanvasBoite.CanvasListIma,
                                             int(self.CanvasBoite.wsize * 0.01),
                                             int(self.CanvasBoite.wsize * 0.67),
                                             int(self.CanvasBoite.hsize * 0.81), tk.CENTER,
                                             AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0)))

            self.EntryQuant[-1].EntryData.config(justify='center')
            self.EntryQuant[-1].Data.set(Mat[12])
            self.QuantInit.append(Mat[12])
            self.ListLieu.append("SPECTROQUANT")

        self.QuantParLieu = [i for i in self.QuantInit]

        QuantTot = ''
        QuantMin = ''
        if Mat[13] is not None and Mat[13] != '':
            QuantTot = Mat[13]
            self.QuantTot = int(QuantTot)
            self.QuantTotInit = self.QuantTot
        if Mat[14] is not None and Mat[14] != '':
            QuantMin = Mat[14]
        self.CanvasBoite.CanvasListIma.create_text(
            int(self.CanvasBoite.wsize * 0.18), int(self.CanvasBoite.hsize * 0.88), text='Stock - Quantité totale: ',
            font=AppliFont('Helvetica', self.SizeFont + 1, 'bold', 0), anchor=tk.W)
        self.QuantStock = LabelInCanvas(self.CanvasBoite.CanvasListIma, QuantTot, '#C0C0C0',
                                        AppliFont('Helvetica', self.SizeFont + 2, 'bold', 0),
                                        int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.88),
                                        tk.CENTER)
        if QuantMin != '':
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.18), int(self.CanvasBoite.hsize * 0.92),
                text='Stock - Quantité minimale: ',
                font=AppliFont('Helvetica', self.SizeFont, 'bold', 0), anchor=tk.W)
            self.CanvasBoite.CanvasListIma.create_text(
                int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.92), text=QuantMin,
                font=AppliFont('Helvetica', self.SizeFont, 'bold', 0), anchor=tk.CENTER, fill='blue')

        for i in range(len(self.EntryQuant)):
            def GestEvt(evt, j=i):
                return self.ModifQuant(evt, j)

            self.EntryQuant[i].EntryData.bind('<KeyRelease>', GestEvt)

    def ModifQuant(self, _, j):
        try:
            self.QuantParLieu[j] = int(self.EntryQuant[j].Data.get())
            self.CalculQuantStock()
        except:
            self.EntryQuant[j].Data.set(self.QuantInit[j])
            self.CalculQuantStock()

    def CalculQuantStock(self):
        self.QuantTot = 0
        for i in range(len(self.EntryQuant)):
            self.QuantTot = self.QuantTot + int(self.EntryQuant[i].Data.get())
        self.QuantStock.Label['text'] = str(self.QuantTot)
        self.QuantToDeStock = self.QuantTot - self.QuantTotInit + self.QuantToDeStockInit
        self.QuantDeStock.Label['text'] = str(self.QuantToDeStock)

    def Valid(self, _):
        self.BtnOK.CanvasBtn.itemconfig(self.BtnOK.ImgCanvasBtn, image=self.BtnOK.ImgBtn[0])
        if self.QuantToDeStock == 0:
            for i in range(len(self.ListLieu)):
                if self.MainAppli.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
                    self.MainAppli.MainAppli.MainAppli.cur.execute(
                        "UPDATE MATERIEL SET'" + self.ListLieu[i] + "' ='" + str(
                            self.QuantParLieu[i]) + "' WHERE " + 'NOMS="' + self.Mat[0] + '"')
                    self.MainAppli.MainAppli.MainAppli.DataBaseChimie.commit()
                    self.MainAppli.MainAppli.MainAppli.SaveListModifDTB('Chimie',
                                                                        'Mise à jour - Stock matériel - Cause HS - '
                                                                        + self.Mat[0])
                elif self.MainAppli.MainAppli.MainAppli.BaseEnCours == "PHYS":
                    self.MainAppli.MainAppli.MainAppli.curphys.execute(
                        "UPDATE MATERIEL SET'" + self.ListLieu[i] + "' ='" + str(
                            self.QuantParLieu[i]) + "' WHERE " + 'NOMS="' + self.Mat[0] + '"')
                    self.MainAppli.MainAppli.MainAppli.DataBasePhys.commit()
                    self.MainAppli.MainAppli.MainAppli.SaveListModifDTB('Physique',
                                                                        'Mise à jour - Stock matériel - Cause HS - '
                                                                        + self.Mat[0])
            if self.MainAppli.MainAppli.MainAppli.BaseEnCours == "CHIMIE":
                self.MainAppli.MainAppli.MainAppli.cur.execute(
                    "UPDATE MATERIEL SET QSTOCK ='" + str(self.QuantTot) + "' WHERE " + 'NOMS="' + self.Mat[0] + '"')
                self.MainAppli.MainAppli.MainAppli.DataBaseChimie.commit()
                self.MainAppli.MainAppli.MainAppli.SaveListModifDTB('Chimie',
                                                                    'Mise à jour - Stock total matériel - Cause HS - '
                                                                    + self.Mat[0])

            self.MainAppli.MajMatHS(self.MainAppli.EntryMat.EntryData.get(), self.MainAppli.Classe.get(),
                                    int(self.MainAppli.EntryQuant.Data.get()))
            self.MainAppli.AffichMatHS()
            self.Annul(_)
        else:
            tkMB.showwarning('Attention', "La quantité de matériel à déstocker n'est pas nulle!", parent=self)
            self.lift()

    def Annul(self, _):
        self.MainAppli.InitSelectMat()
        self.destroy()
