from AppliDef import *
from FrmInfoProdMat import InfoMatPhys


class FrmAjoutTPPhys(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.NlineMat = 1
        self.NColMat = 3
        self.InfoMat = None
        self.ListMat = None
        self.ListMatTP = []
        self.TabMat = None
        self.MenuClicDroitTabMat = []
        self.TitreMat = None
        self.IndexElt = None
        self.EntryMat = None
        self.ListBoxMats = None
        self.ListMats = None
        self.TitreQuant = None
        self.QuantMat = None
        self.BtnPlus = None
        self.BtnMoins = None
        self.LinePar = None
        self.LieuListe = []
        self.Lieu = None
        self.ListeLieu = None
        self.WindowListeLieu = None
        self.BtnOK2 = None
        self.BtnAnnul2 = None
        self.LineSelect = None
        self.ModifenCours = False
        self.PathFilePDFToOpen = ''
        self.ListTitreTP = []
        self.Page1PDF = None
        self.Page2PDF = None
        self.PageAffich = 0
        self.NbrPagesPDF = 0
        self.FichierPDFAOuvrir = ''
        self.ModifTPenCours = False
        self.ActionModifTitre = False
        self.MenuClicDroitPDF = None
        self.PDF = ''
        self.TitreTPPDF = None
        self.DocPDFInit = ''

        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)))

        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.CacheFrmAjout)

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

        self.EntryTitre = EntryData(self.CanvasFrmFond, int(self.SX * 0.03),
                                    int(self.SX * 0.5), int(self.SY * 0.08), tk.CENTER,
                                    AppliFont('Helvetica', self.MainAppli.SizeFont + 10, 'bold', 0))
        self.EntryTitre.EntryData.bind('<KeyRelease>', self.ModifTitre)

        self.ClasseListe = self.MainAppli.ListClasses
        Cat = ''

        if self.MainAppli.ModifEnCours:
            if self.MainAppli.NAction == 3011:
                self.TP = self.MainAppli.ListRecherch[self.MainAppli.IndexElt]
            elif self.MainAppli.NAction == 3022:
                self.TP = self.MainAppli.ListTPCat[self.MainAppli.IndexElt]
            else:
                self.TP = self.MainAppli.ListTPs[self.MainAppli.IndexElt]

            self.TitreTP = self.TP[0]
            textClasse = self.TP[2]
            self.EntryTitre.Data.set(self.TitreTP)
            textlabelTag = 'Modifier un TP de physique'
            self.TextAction = 'Mise à jour - TP - '
        else:
            self.TitreTP = ''
            self.EntryTitre.Data.set('Titre du TP')
            textlabelTag = 'Ajouter un TP de physique'
            self.TextAction = 'Ajout - TP - '
            textClasse = self.ClasseListe[0]
            self.EntryTitre.EntryData.bind('<KeyRelease>', self.ModifTitre)
        self.EntryTitre.EntryData.config(justify='center')

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond, textlabelTag, '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)

        self.TitreClasse = self.CanvasFrmFond.create_text(
            int(self.SX * 0.01), int(self.SY * 0.045), text='Classe',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 1), anchor=tk.W)

        self.Classe = tk.StringVar()
        self.Classe.set(textClasse)
        self.ListeClasse = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.02), textvariable=self.Classe,
                                           values=self.ClasseListe)
        self.CanvasFrmFond.create_window(int(self.SX * 0.01), int(self.SY * 0.07), anchor=tk.NW,
                                         window=self.ListeClasse)

        self.BtnImportPDF = BtnAction(self.CanvasFrmFond, int(self.SX * 0.987), int(self.SY * 0.055), self.RatioX,
                                      self.RatioY, 'Media/FrmAjout/BtnPDF/')
        self.BtnImportPDF.CanvasBtn.bind('<ButtonRelease-1>', self.ChargePDF)

        self.CanvasMenu1 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.8), int(self.SX * 0.003), int(self.SY * 0.15), tk.NW)

        self.CanvasMenu1 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.8), int(self.SX * 0.003), int(self.SY * 0.15), tk.NW)

        self.AffichMat()

        self.CanvasMenu2 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.8), int(self.SX * 0.5), int(self.SY * 0.15), tk.N)
        self.CanvasMenu2.CanvasMenu.itemconfig(self.CanvasMenu2.ImgCanvasMenu, image=self.CanvasMenu2.ImgMenu[1])
        self.CanvasMenu2.CanvasMenu.bind('<MouseWheel>', self.MouseWheelDefil)

        self.CanvasMenu3 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.8), int(self.SX * 0.832), int(self.SY * 0.15), tk.N)
        self.CanvasMenu3.CanvasMenu.itemconfig(self.CanvasMenu3.ImgCanvasMenu, image=self.CanvasMenu3.ImgMenu[2])
        self.CanvasMenu3.CanvasMenu.bind('<MouseWheel>', self.MouseWheelDefil)

        if not self.MainAppli.ModifEnCours:
            self.AffichTitre()
        else:
            if self.TP[1] is not None and self.TP[1] != '':
                self.FichierPDFAOuvrir = 'Datas/PDFTPPhys/' + self.TP[1] + '.pdf'
                self.DocPDFInit = self.TP[1]
                self.AffichPDF(self.FichierPDFAOuvrir)
            else:
                self.AffichTitre()
            if self.TP[3] is not None and self.TP[3] != '':
                Cat = self.TP[3]
            else:
                Cat = ''

        self.CanvasFrmFond.create_text(
            int(self.SX * 0.01), int(self.SY * 0.975), text='Catégorie :',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 1), anchor=tk.W)

        self.EntryCat = EntryData(self.CanvasFrmFond, int(self.SX * 0.028),
                                  int(self.SX * 0.07), int(self.SY * 0.975), tk.W,
                                  AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0))
        self.EntryCat.Data.set(Cat)
        self.EntryCat.EntryData.bind('<Return>', self.ModifCat)

        self.BtnOK = BtnAction(self.CanvasFrmFond, int(self.SX * 0.962), int(self.SY * 0.975), self.RatioX * 0.15,
                               self.RatioX * 0.15, 'Media/FrmAjout/BtnOK/')
        self.BtnAnnul = BtnAction(self.CanvasFrmFond, int(self.SX * 0.985), int(self.SY * 0.975), self.RatioX * 0.15,
                                  self.RatioX * 0.15, 'Media/FrmAjout/BtnAnnul/')
        ChangeCursor(self.BtnAnnul.CanvasBtn)
        ChangeCursor(self.BtnOK.CanvasBtn)
        self.BtnAnnul.CanvasBtn.bind('<ButtonRelease-1>', self.CacheFrmAjout)
        self.BtnOK.CanvasBtn.bind('<ButtonRelease-1>', self.SaveNewTP)

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

        self.CanvasFrmFond.pack()

    def AffichMat(self):
        LabelInCanvas(self.CanvasMenu1.CanvasMenu, 'Matériel du TP', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.002), tk.NW)

        if self.MainAppli.ModifEnCours:
            self.MainAppli.curphys.execute("SELECT " + "MATERIEL, QUANTITE, LIEU" +
                                           " FROM TP WHERE TITRE = \"" + self.TitreTP + "\" order by MATERIEL")
            self.ListMat = self.MainAppli.curphys.fetchall()
            nl = 0
            for i in range(len(self.ListMat)):
                if self.ListMat[i][0] != '' and self.ListMat[i][0] is not None:
                    nl = nl + 1
            self.NlineMat = nl + 1

            self.TabMat = TableauMain(self.CanvasMenu1.CanvasMenu, self.NlineMat, self.NColMat,
                                      ['Désignation', 'Quantité', 'Lieu'], [0.079, 0.02, 0.02],
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0))

            nl = 0
            self.ListMatTP = []
            for i in range(len(self.ListMat)):
                if self.ListMat[i][0] != '' and self.ListMat[i][0] is not None:
                    for j in range(3):
                        self.TabMat.TabLabels[nl][j]['text'] = self.ListMat[i][j]
                    self.ListMatTP.append([self.ListMat[i][0], self.ListMat[i][1], self.ListMat[i][2]])
                    nl = nl + 1
        else:
            self.TabMat = TableauMain(self.CanvasMenu1.CanvasMenu, self.NlineMat, self.NColMat,
                                      ['Désignation', 'Quantité', 'Lieu'], [0.079, 0.02, 0.02],
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0))
        self.ListMatTP.append(['', '', ''])
        self.AjoutMenuMat()

    def ReAffichMat(self):
        self.TabMat = TableauMain(self.CanvasMenu1.CanvasMenu, self.NlineMat, self.NColMat,
                                  ['Désignation', 'Quantité', 'Lieu'], [0.079, 0.02, 0.02],
                                  AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                  AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0))
        self.AjoutMenuMat()
        for r in range(self.NlineMat):
            self.TabMat.TabLabels[r][0]['text'] = self.ListMatTP[r][0]
            self.TabMat.TabLabels[r][1]['text'] = self.ListMatTP[r][1]
            self.TabMat.TabLabels[r][2]['text'] = self.ListMatTP[r][2]

    def AjoutMenuMat(self):
        self.MenuClicDroitTabMat = []
        for r in range(self.NlineMat):
            ListMenu = []
            for i in range(self.NColMat):
                ListMenu.append(tk.Menu(self.TabMat.TabLabels[r][i], tearoff=0))

                def GestEvt(evt, j=r):
                    return self.AffichMenuClicDroit(evt, self.MenuClicDroitTabMat, j)

                self.TabMat.TabLabels[r][i].bind("<Button-3>", GestEvt)
            self.MenuClicDroitTabMat.append(ListMenu)

        for r in range(self.TabMat.NLine):
            if r == self.TabMat.NLine - 1:
                self.MenuClicDroitTabMat[r][0].add_command(label="Ajouter un matériel", command=self.AjoutMateriel)
            else:
                self.MenuClicDroitTabMat[r][0].add_command(label="Modifier le matériel", command=self.ModifMateriel)
                self.MenuClicDroitTabMat[r][0].add_command(label="Supprimer le matériel", command=self.SupMateriel)

    def AjoutMateriel(self):
        self.ModifTPenCours = True
        self.EffaceMenu2()
        LabelInCanvas(self.CanvasMenu2.CanvasMenu, 'Ajouter du matériel à la fiche TP', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.002), tk.NW)

        self.TitreMat = self.CanvasMenu2.CanvasMenu.create_text(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.05), text='Sélection du matériel',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 1), anchor=tk.W)

        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.09), tk.CENTER,
                                  AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0))
        self.EntryMat.Data.set('')
        self.EntryMat.EntryData.config(justify='center')
        self.EntryMat.EntryData.bind('<KeyRelease>', self.ModifMat)

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

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

        self.MainAppli.curphys.execute("select " + self.MainAppli.ListChampsTabMatPhys + " from MATERIEL order by NOMS")
        self.ListMats = self.MainAppli.curphys.fetchall()

        self.ListBoxMats.ListBox.delete(0, tk.END)
        for i in range(len(self.ListMats)):
            self.ListBoxMats.ListBox.insert(tk.END, self.ListMats[i][0])
        self.ListBoxMats.ListBox.selection_set(0)
        self.AffichStock(0)
        self.EntryMat.Data.set(self.ListMats[0][0])

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

        self.QuantMat = LabelInCanvas(self.CanvasMenu2.CanvasMenu, '1', 'white',
                                      AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0),
                                      int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.05),
                                      int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.88), tk.NW)
        self.QuantMat.Label.config(width=int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.006),
                                   height=int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.003), relief=tk.RIDGE)

        self.BtnPlus = BtnAction(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.13),
                                 int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.895), self.RatioX * 1.1,
                                 self.RatioX * 1.1, 'Media/FrmAjout/BtnPlus/')
        self.BtnPlus.CanvasBtn.bind('<ButtonRelease-1>', self.QuantMatPlus)
        self.BtnMoins = BtnAction(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.13),
                                  int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.915), self.RatioX * 1.1,
                                  self.RatioX * 1.1, 'Media/FrmAjout/BtnMoins/')
        self.BtnMoins.CanvasBtn.bind('<ButtonRelease-1>', self.QuantMatMoins)
        self.LinePar = self.CanvasMenu2.CanvasMenu.create_line(int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.19),
                                                               int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.92),
                                                               int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.21),
                                                               int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.89),
                                                               width=2)

        self.LieuListe = ["Poste TP", "Bureau"]
        self.Lieu = tk.StringVar()
        self.Lieu.set(self.LieuListe[0])
        self.ListeLieu = ListeDeroulante(self.CanvasFrmFond, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.02),
                                         textvariable=self.Lieu,
                                         values=self.LieuListe)
        self.WindowListeLieu = self.CanvasMenu2.CanvasMenu.create_window(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.25),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.893), anchor=tk.NW, window=self.ListeLieu)

        self.BtnOK2 = 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.BtnOK2.CanvasBtn.bind('<ButtonRelease-1>', self.ValidAjoutMat)
        self.BtnAnnul2 = 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.BtnAnnul2.CanvasBtn.bind('<ButtonRelease-1>', self.AnnulAjoutMat)

    def AffichMenuClicDroit(self, event, MenuClicDroitTab, j):
        if self.InfoMat is None:
            MenuClicDroitTab[j][0].post(event.x_root, event.y_root)
            self.LineSelect = j

    def ModifCat(self, _):
        self.MainAppli.curphys.execute('SELECT CAT'
                                       ' FROM TP WHERE CAT LIKE \"%' + self.EntryCat.EntryData.get() +
                                       '%\" order by CAT')
        Cat = self.MainAppli.curphys.fetchall()
        if len(Cat) > 0:
            self.EntryCat.Data.set(Cat[0][0])

    def ModifMat(self, _):
        self.ActionModifMat()

    def ActionModifMat(self):
        self.MainAppli.curphys.execute('SELECT ' + self.MainAppli.ListChampsTabMatPhys +
                                       ' FROM MATERIEL WHERE NOMS LIKE \"%' +
                                       self.EntryMat.Data.get() + '%\" order by NOMS')
        self.ListMats = self.MainAppli.curphys.fetchall()
        self.ListBoxMats.ListBox.delete(0, tk.END)
        for i in range(len(self.ListMats)):
            self.ListBoxMats.ListBox.insert(tk.END, self.ListMats[i][0])
        self.ListBoxMats.ListBox.selection_set(0)
        if len(self.ListMats) > 0:
            self.AffichStock(0)
        else:
            self.EffaceMenu3()

    def OnSelectListBox(self, evt):
        try:
            w = evt.widget
            self.IndexElt = int(w.curselection()[0])
            if self.InfoMat is not None:
                self.EntryMat.Data.set(self.ListMats[self.IndexElt][0])
                self.AffichStock(self.IndexElt)

        except:
            pass

    def AffichStock(self, Nmat):
        self.EffaceMenu3()
        LabelInCanvas(self.CanvasMenu3.CanvasMenu, 'Informations sur le matériel sélectionné', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.002), tk.NW)
        self.InfoMat = InfoMatPhys(self.CanvasMenu3.CanvasMenu, self.ListMats[Nmat],
                                   self.MainAppli.curphys, self.MainAppli.SizeFont, self.RatioX, self.RatioY, 2,
                                   self.MainAppli.LieuxStockMatPhys)

    def EffaceMenu3(self):
        for widget in self.CanvasMenu3.CanvasMenu.winfo_children():
            widget.destroy()
        if self.InfoMat is not None:
            self.CanvasMenu3.CanvasMenu.delete(self.InfoMat.NomMat)
            self.CanvasMenu3.CanvasMenu.delete(self.InfoMat.TitreStock)
            self.CanvasMenu3.CanvasMenu.delete(self.InfoMat.TitreFournisseur)
            self.InfoMat = None
        self.CanvasMenu3.CanvasMenu.itemconfig(self.CanvasMenu3.ImgCanvasMenu, image=self.CanvasMenu3.ImgMenu[0])
        if self.Page2PDF is not None:
            self.CanvasMenu3.CanvasMenu.delete(self.Page2PDF.ImgCanvasDoc)

    def EffaceMenu2(self):
        for widget in self.CanvasMenu2.CanvasMenu.winfo_children():
            widget.destroy()
        self.CanvasMenu2.CanvasMenu.delete(self.TitreQuant)
        self.CanvasMenu2.CanvasMenu.delete(self.TitreMat)
        self.CanvasMenu2.CanvasMenu.delete(self.LinePar)
        self.CanvasMenu2.CanvasMenu.delete(self.WindowListeLieu)
        self.CanvasMenu2.CanvasMenu.itemconfig(self.CanvasMenu2.ImgCanvasMenu, image=self.CanvasMenu2.ImgMenu[0])
        if self.Page1PDF is not None:
            self.CanvasMenu2.CanvasMenu.delete(self.Page1PDF.ImgCanvasDoc)

    def QuantMatPlus(self, _):
        self.BtnPlus.CanvasBtn.itemconfig(self.BtnPlus.ImgCanvasBtn, image=self.BtnPlus.ImgBtn[0])
        self.QuantMat.Label.config(text=str(int(self.QuantMat.Label['text']) + 1))

    def QuantMatMoins(self, _):
        self.BtnMoins.CanvasBtn.itemconfig(self.BtnMoins.ImgCanvasBtn, image=self.BtnMoins.ImgBtn[0])
        if int(self.QuantMat.Label['text']) > 1:
            self.QuantMat.Label.config(text=str(int(self.QuantMat.Label['text']) - 1))

    def ValidAjoutMat(self, _):
        if self.EntryMat.EntryData.get() != '':
            if not self.ModifenCours:
                Nline = self.NlineMat - 1
            else:
                Nline = self.LineSelect
            self.ListMatTP[Nline][0] = self.EntryMat.EntryData.get()
            self.TabMat.TabLabels[Nline][0]['text'] = self.EntryMat.EntryData.get()
            self.ListMatTP[Nline][1] = self.QuantMat.Label['text']
            self.TabMat.TabLabels[Nline][1]['text'] = self.QuantMat.Label['text']
            self.ListMatTP[Nline][2] = self.Lieu.get()
            self.TabMat.TabLabels[Nline][2]['text'] = self.Lieu.get()

            if not self.ModifenCours:
                self.TabMat.AjoutLine()
                self.NlineMat = self.NlineMat + 1
                self.ListMatTP.append(['', '', ''])
                self.AjoutMenuMat()

            self.AnnulAjoutMat(_)
        else:
            tkMB.showwarning('Attention', "Veuillez choisir un matériel!")
            self.lift()

    def AnnulAjoutMat(self, _):
        self.ModifTPenCours = False
        self.ModifenCours = False
        self.EffaceMenu2()
        self.EffaceMenu3()
        self.CanvasMenu2.CanvasMenu.itemconfig(self.CanvasMenu2.ImgCanvasMenu, image=self.CanvasMenu2.ImgMenu[1])
        self.CanvasMenu3.CanvasMenu.itemconfig(self.CanvasMenu3.ImgCanvasMenu, image=self.CanvasMenu3.ImgMenu[2])
        if self.PathFilePDFToOpen != '' or self.FichierPDFAOuvrir != '':
            self.AffichPagesPDF(self.PageAffich)

    def ModifMateriel(self):
        self.ModifenCours = True
        self.AjoutMateriel()
        self.EntryMat.Data.set(self.TabMat.TabLabels[self.LineSelect][0]['text'])
        self.QuantMat.Label['text'] = self.TabMat.TabLabels[self.LineSelect][1]['text']
        self.Lieu.set(self.TabMat.TabLabels[self.LineSelect][2]['text'])
        self.ActionModifMat()

    def SupMateriel(self):
        del self.ListMatTP[self.LineSelect]
        self.NlineMat = self.NlineMat - 1
        self.ReAffichMat()

    def ChargePDF(self, _):
        self.BtnImportPDF.CanvasBtn.itemconfig(self.BtnImportPDF.ImgCanvasBtn, image=self.BtnImportPDF.ImgBtn[0])
        if not self.ModifTPenCours:
            self.PathFilePDFToOpen = tkfiledialog.askopenfilename(title="Ouvrir un fichier",
                                                                  filetypes=[('PDF files', '.pdf')])
            self.lift(self.parent)
            if self.PathFilePDFToOpen != '':
                self.AffichPDF(self.PathFilePDFToOpen)
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def AffichPDF(self, file):
        self.PDF = file
        if self.Page1PDF is not None:
            self.CanvasMenu2.CanvasMenu.delete(self.Page1PDF.ImgCanvasDoc)
            self.Page1PDF = None
        if self.Page2PDF is not None:
            self.CanvasMenu3.CanvasMenu.delete(self.Page2PDF.ImgCanvasDoc)
            self.Page2PDF = None
        if self.TitreTPPDF is not None:
            self.CanvasMenu2.CanvasMenu.delete(self.TitreTPPDF)
        self.PageAffich = 0

        self.Page1PDF = PagePDF(self.CanvasMenu2.CanvasMenu, file,
                                int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.8),
                                int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                                int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.5), 0)
        self.NbrPagesPDF = self.Page1PDF.NbrPagesPDF

        self.CanvasMenu2.CanvasMenu.bind('<Double-1>', self.OuvrePDF)
        self.MenuClicDroitPDF = tk.Menu(self.CanvasMenu2.CanvasMenu, tearoff=0)
        self.MenuClicDroitPDF.add_command(label="Ouvrir dans le navigateur", command=self.ActionOuvrePDF)
        self.MenuClicDroitPDF.add_separator()
        self.MenuClicDroitPDF.add_command(label="Effacer le document", command=self.ActionSupPDF)
        self.CanvasMenu2.CanvasMenu.bind("<Button-3>", self.AffichMenuClicDroitPDF)

        if self.NbrPagesPDF - 1 > 0:
            self.Page2PDF = PagePDF(self.CanvasMenu3.CanvasMenu, file,
                                    int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.8),
                                    int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.5),
                                    int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.5), 1)

    def AffichPagesPDF(self, npage):
        if self.Page1PDF is not None:
            self.CanvasMenu2.CanvasMenu.delete(self.Page1PDF.ImgCanvasDoc)
        if self.Page2PDF is not None:
            self.CanvasMenu3.CanvasMenu.delete(self.Page2PDF.ImgCanvasDoc)
        self.Page1PDF.ImgCanvasDoc = self.CanvasMenu2.CanvasMenu.create_image(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5), int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.5),
            anchor=tk.CENTER, image=self.Page1PDF.PDF[npage])
        if npage + 1 < self.NbrPagesPDF:
            self.Page2PDF.ImgCanvasDoc = self.CanvasMenu3.CanvasMenu.create_image(
                int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.5),
                int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.5),
                anchor=tk.CENTER, image=self.Page2PDF.PDF[npage + 1])

    def MouseWheelDefil(self, event):
        if event.delta == -120:
            if self.PageAffich > 1:
                self.PageAffich = self.PageAffich - 2
                self.AffichPagesPDF(self.PageAffich)
            else:
                self.AffichPagesPDF(0)
        if event.delta == 120:
            if self.PageAffich < self.NbrPagesPDF - 2:
                self.PageAffich = self.PageAffich + 2
                self.AffichPagesPDF(self.PageAffich)
            elif (self.NbrPagesPDF % 2) != 0:
                self.AffichPagesPDF(self.NbrPagesPDF - 1)

    def SaveNewTP(self, _):
        self.BtnOK.CanvasBtn.itemconfig(self.BtnOK.ImgCanvasBtn, image=self.BtnOK.ImgBtn[0])
        if self.EntryTitre.EntryData.get() != '' and not self.ModifTPenCours:
            Rep = True
            self.MainAppli.curphys.execute("Select * from TP where " + 'TITRE = "' + self.EntryTitre.EntryData.get() +
                                           '"')
            NOcur = len(self.MainAppli.curphys.fetchall())

            if NOcur > 0:
                Rep = tkMB.askyesno('Attention', 'Un TP nommé "' + self.EntryTitre.EntryData.get()
                                    + '" est déja présent dans la base de données, souhaitez-vous mettre à jour '
                                      'les données?', parent=self)
            if Rep:
                if NOcur > 0:
                    SQLRequet = "DELETE FROM TP WHERE " + 'TITRE = "' + self.EntryTitre.EntryData.get() + '"'
                    self.MainAppli.curphys.execute(SQLRequet)
                    self.MainAppli.DataBaseChimie.commit()

                Titre = self.EntryTitre.EntryData.get()
                NomSave = ModifString(self.EntryTitre.EntryData.get())
                self.MainAppli.curphys.execute("Select TITRE from TP")
                LNoms = self.MainAppli.curphys.fetchall()
                Ocur = False
                for i in range(len(LNoms)):
                    if ModifString(LNoms[i][0]) == NomSave:
                        Ocur = True
                        break
                if Ocur:
                    NomSave = ModifString(NomSave + str(datetime.now()))

                Classe = self.Classe.get()
                PDF = ''
                Cat = self.EntryCat.EntryData.get()
                if self.PathFilePDFToOpen != '':
                    PDF = NomSave
                    shutil.copy(self.PathFilePDFToOpen, 'Datas/PDFTPPhys/' + PDF + '.pdf')
                elif self.ActionModifTitre:
                    if self.FichierPDFAOuvrir != '':
                        PDF = NomSave
                        if not os.path.exists('Datas/PDFTPPhys/' + PDF + '.pdf'):
                            shutil.copy('Datas/PDFTPPhys/' + self.TP[1] + '.pdf', 'Datas/PDFTPPhys/' + PDF + '.pdf')
                elif self.FichierPDFAOuvrir != '':
                    PDF = self.TP[1]

                if self.ListMatTP[0][0] == '':
                    data = [(Titre, PDF, Classe, Cat)]
                    self.MainAppli.curphys.execute(
                        "INSERT INTO TP(" + self.MainAppli.ListChampsTabTPPhys + ") VALUES(?,?,?,?)", data[0])
                else:
                    for r in range(self.NlineMat - 1):
                        data = [(Titre, PDF, Classe, self.ListMatTP[r][0], self.ListMatTP[r][1], self.ListMatTP[r][2],
                                 Cat)]
                        self.MainAppli.curphys.execute(
                            "INSERT INTO TP(" + self.MainAppli.ListChampsTabTPPhys2 + ") VALUES(?,?,?,?,?,?,?)",
                            data[0])

                self.MainAppli.DataBasePhys.commit()
                self.MainAppli.SaveListModifDTB('Physique', self.TextAction + Titre)
                self.MainAppli.curphys.execute("select " + self.MainAppli.ListChampsTabTP +
                                               " from TP order by TITRE")
                self.MainAppli.ListTP = self.MainAppli.curphys.fetchall()

                self.MainAppli.ListTPs = []
                for i in self.MainAppli.ListTP:
                    if i not in self.MainAppli.ListTPs:
                        self.MainAppli.ListTPs.append(i)

                if PDF != self.DocPDFInit and not self.ActionModifTitre and self.DocPDFInit != '':
                    if os.path.exists('Datas/PDFTPPhys/' + self.DocPDFInit + '.pdf'):
                        os.remove('Datas/PDFTPPhys/' + self.DocPDFInit + '.pdf')

                if self.MainAppli.ModifEnCours:
                    if self.MainAppli.OldNAction == 3:
                        self.MainAppli.ChargeListProduits(self.MainAppli.ListTPs)
                        self.MainAppli.AffichEtagProduits(self.MainAppli.ListTPs)
                    elif self.MainAppli.OldNAction == 3011:
                        self.MainAppli.NAction = 301
                        self.MainAppli.ActionRecherche()
                    elif self.MainAppli.OldNAction == 3022:
                        self.MainAppli.AffichListTPCat(self.MainAppli.NSCatselected)
                else:
                    self.MainAppli.ChargeListProduits(self.MainAppli.ListTPs)
                    self.MainAppli.AffichEtagProduits(self.MainAppli.ListTPs)

                try:
                    self.MainAppli.IndexElt = self.MainAppli.ListNomProd.index(Titre)
                    self.MainAppli.FrmTP.SelectTP(self.MainAppli.IndexElt)
                except:
                    pass

                self.CacheFrmAjout(_)
            else:
                self.lift()
        else:
            if not self.ModifTPenCours:
                tkMB.showwarning('Attention', "Veuillez indiquer le nom du TP!")
                self.lift()
            else:
                winsound.PlaySound("*", winsound.SND_ASYNC)

    def ModifTitre(self, _):
        if self.EntryTitre.EntryData.get() != self.TitreTP:
            self.ActionModifTitre = True
        else:
            self.ActionModifTitre = False
        if self.PDF == '':
            self.AffichTitre()

    def AffichTitre(self):
        if self.TitreTPPDF is not None:
            self.CanvasMenu2.CanvasMenu.delete(self.TitreTPPDF)
        if len(self.ListTitreTP) > 0:
            for i in range(len(self.ListTitreTP)):
                self.CanvasMenu2.CanvasMenu.delete(self.ListTitreTP[i])
        ListTitreTP = []
        if len(self.EntryTitre.Data.get()) > 55:
            TitreTP = self.EntryTitre.Data.get().split(' ')
            titre = TitreTP[0]
            for i in range(1, len(TitreTP)):
                if len(titre + ' ' + TitreTP[i]) < 56:
                    titre = titre + ' ' + TitreTP[i]
                else:
                    ListTitreTP.append(titre)
                    titre = TitreTP[i]
            ListTitreTP.append(titre)
            self.ListTitreTP = []
            for i in range(len(ListTitreTP)):
                self.ListTitreTP.append(self.CanvasMenu2.CanvasMenu.create_text(
                    int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                    int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.2 + i * self.SY * 0.05), text=ListTitreTP[i],
                    font=AppliFont('Calibri', self.MainAppli.SizeFont + 6, 'bold', 0), anchor=tk.CENTER))
        else:
            self.TitreTPPDF = self.CanvasMenu2.CanvasMenu.create_text(
                int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.2), text=self.EntryTitre.Data.get(),
                font=AppliFont('Calibri', self.MainAppli.SizeFont + 6, 'bold', 0), anchor=tk.CENTER)

    def OuvrePDF(self, _):
        self.ActionOuvrePDF()

    def ActionOuvrePDF(self):
        AffichPDF(self.EntryTitre.EntryData.get(), self.PDF, self)

    def ActionSupPDF(self):
        if self.Page1PDF is not None:
            self.CanvasMenu2.CanvasMenu.delete(self.Page1PDF.ImgCanvasDoc)
            self.Page1PDF = None
        if self.Page2PDF is not None:
            self.CanvasMenu3.CanvasMenu.delete(self.Page2PDF.ImgCanvasDoc)
            self.Page2PDF = None
        self.AffichTitre()
        self.PathFilePDFToOpen = ''
        self.FichierPDFAOuvrir = ''
        self.MainAppli.parent.lift()
        self.MainAppli.FrmLift()

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

    def AffichMenuClicDroitPDF(self, event):
        self.MenuClicDroitPDF.post(event.x_root, event.y_root)

    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 CacheFrmAjout(self, _):
        self.BtnAnnul.CanvasBtn.itemconfig(self.BtnAnnul.ImgCanvasBtn, image=self.BtnAnnul.ImgBtn[0])
        if not self.ModifTPenCours:
            self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
            self.MainAppli.ListBtnActionV[2].CanvasBtn.itemconfig(self.MainAppli.ListBtnActionV[2].ImgCanvasBtn,
                                                                  image=self.MainAppli.ListBtnActionV[2].ImgBtn[0])
            self.destroy()
            if self.MainAppli.OldNAction != 0:
                self.MainAppli.NAction = self.MainAppli.OldNAction
            else:
                self.MainAppli.NAction = 3
            self.MainAppli.MAJInfo()
            self.MainAppli.parent.focus_force()
            self.MainAppli.FrmLift()
            self.MainAppli.ModifEnCours = False
            self.ModifenCours = False
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)
