from AppliDef import *
import shutil
from pathlib import Path
from FrmAjoutModifProd import ChargeEntry, FrmModifFour


class FrmAjoutMat(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.DocPDF = False
        self.FrmPDF = None
        self.PathFilePDFToOpen = ''
        self.QTotal = 0
        self.PathFileFournisseurToOpen = ''
        self.PathFilejpgToOpen = ''
        self.CanvasContVisuelMat = None
        self.ImgVisuelMat = []
        self.img = None
        self.ImgCanvasContVisuelMat = None
        self.MenuClicDroitVisuelMat = None
        self.ImgCanvasImgEtiqMat = None
        self.CanvasImgEtiqMat = None
        self.ImgEtiqMat = []
        self.Visuel = ''
        self.Fournisseur = ''
        self.Notice = ''
        self.QCOM = ''
        self.QCOMANNUL = ''
        self.QENCOM = ''
        self.ActionModifNom = False
        self.NDescript = 0
        self.ListFours = []
        self.FrmModifFour = None
        self.NRefFour = 0
        self.NoticeInit = ''
        self.VisuelInit = ''
        self.FileDescriptInit = ''
        self.NomInit = ''

        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)

        if self.MainAppli.BaseEnCours == "CHIMIE":
            Type = 'Chimie'
        else:
            Type = 'Physique'

        if self.MainAppli.ModifEnCours:
            textlabelTag = 'Modifier un matériel de ' + Type
        else:
            textlabelTag = 'Ajouter un matériel de ' + Type
        coefY = float(ConfigResolution(self.MainAppli.Nconfig, 'YTitreFrm', self.MainAppli.curSave))
        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.CanvasMenu1 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.282),
                                      int(self.SY * 0.967), int(self.SX * 0.003), int(self.SY * 0.03), tk.NW)

        LabelInCanvas(self.CanvasMenu1.CanvasMenu, 'Stock / Fournisseur', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.005), tk.NW)

        self.EntryNom = EntryData(self.CanvasMenu1.CanvasMenu, int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.1),
                                  int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.5),
                                  int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.06), tk.CENTER,
                                  AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0))
        self.EntryNom.Data.set('Nom du matériel')
        self.EntryNom.EntryData.config(justify='center')
        self.EntryNom.EntryData.bind('<KeyRelease>', self.ModifNom)

        self.TitreStock = self.CanvasMenu1.CanvasMenu.create_text(
            int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.05),
            int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.11), text='Stock',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 1), anchor=tk.W)

        self.CanvasBoite = CanvasInWindow('Media/FrmInfo/Boite/', self.RatioX, self.RatioY,
                                          self.CanvasMenu1.CanvasMenu, tk.CENTER,
                                          int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.5),
                                          int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.355), 0)

        self.EntryCatMat = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.08),
                                     int(self.CanvasBoite.wsize * 0.5),
                                     int(self.CanvasBoite.hsize * 0.1), tk.CENTER,
                                     AppliFont('Helvetica', self.MainAppli.SizeFont + 1, 'bold', 0))
        self.EntryCatMat.Data.set('Catégorie du matériel')
        self.EntryCatMat.EntryData.config(justify='center')
        self.EntryCatMat.EntryData.bind('<Return>', self.ModifCat)

        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.MainAppli.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.MainAppli.SizeFont + 1, 'bold', 1), anchor=tk.CENTER)

        if self.MainAppli.BaseEnCours == "CHIMIE":
            Lieux1 = self.MainAppli.LieuxStockMatChim[0]
            Lieux2 = self.MainAppli.LieuxStockMatChim[1]
        else:
            Lieux1 = self.MainAppli.LieuxStockMatPhys[0]
            Lieux2 = self.MainAppli.LieuxStockMatPhys[1]

        LabelInCanvas(self.CanvasBoite.CanvasListIma, Lieux1, '#C0C0C0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                      int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.41), tk.CENTER)

        self.EntryLieuLabo = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.03),
                                       int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.465),
                                       tk.CENTER,
                                       AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
        self.EntryQuantLabo = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.01),
                                        int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.465),
                                        tk.CENTER,
                                        AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
        self.EntryLieuLabo.EntryData.config(justify='center')
        self.EntryQuantLabo.EntryData.config(justify='center')
        self.EntryQuantLabo.EntryData.bind('<KeyRelease>', self.CalculQTot)

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

        self.EntryLieuTP = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.03),
                                     int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.635),
                                     tk.CENTER,
                                     AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
        self.EntryQuantTP = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.01),
                                      int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.635),
                                      tk.CENTER,
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
        self.EntryLieuTP.EntryData.config(justify='center')
        self.EntryQuantTP.EntryData.config(justify='center')
        self.EntryQuantTP.EntryData.bind('<KeyRelease>', self.CalculQTot)

        Lieu3 = ''
        if self.MainAppli.BaseEnCours == 'CHIMIE':
            self.EntryLieuLabo2 = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.03),
                                            int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.515),
                                            tk.CENTER,
                                            AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
            self.EntryQuantLabo2 = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.01),
                                             int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.515),
                                             tk.CENTER,
                                             AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
            self.EntryLieuLabo2.EntryData.config(justify='center')
            self.EntryQuantLabo2.EntryData.config(justify='center')
            self.EntryQuantLabo2.EntryData.bind('<KeyRelease>', self.CalculQTot)
            self.EntryLieuTP2 = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.03),
                                          int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.685),
                                          tk.CENTER,
                                          AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
            self.EntryQuantTP2 = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.01),
                                           int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.685),
                                           tk.CENTER,
                                           AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
            self.EntryLieuTP2.EntryData.config(justify='center')
            self.EntryQuantTP2.EntryData.config(justify='center')
            self.EntryQuantTP2.EntryData.bind('<KeyRelease>', self.CalculQTot)

            Lieu3 = self.MainAppli.LieuxStockMatChim[2]

        elif self.MainAppli.BaseEnCours == 'PHYS':
            Lieu3 = self.MainAppli.LieuxStockMatPhys[2]

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

        self.EntryLieuSpectro = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.03),
                                          int(self.CanvasBoite.wsize * 0.37), int(self.CanvasBoite.hsize * 0.81),
                                          tk.CENTER,
                                          AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
        self.EntryQuantSpectro = 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.MainAppli.SizeFont, 'bold', 0))
        self.EntryLieuSpectro.EntryData.config(justify='center')
        self.EntryQuantSpectro.EntryData.config(justify='center')
        self.EntryQuantSpectro.EntryData.bind('<KeyRelease>', self.CalculQTot)

        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.MainAppli.SizeFont + 1, 'bold', 0), anchor=tk.W)
        self.QTot = self.CanvasBoite.CanvasListIma.create_text(
            int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.88), text='0',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0), anchor=tk.CENTER, fill='blue')

        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.MainAppli.SizeFont, 'bold', 0),
            anchor=tk.W)
        self.EntryQuantMin = EntryData(self.CanvasBoite.CanvasListIma, int(self.CanvasBoite.wsize * 0.01),
                                       int(self.CanvasBoite.wsize * 0.67), int(self.CanvasBoite.hsize * 0.92),
                                       tk.CENTER,
                                       AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
        self.EntryQuantMin.EntryData.config(justify='center')

        self.TitreFournisseur = self.CanvasMenu1.CanvasMenu.create_text(
            int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.05),
            int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.62), text='Fournisseur',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 1), anchor=tk.W)

        self.ListRefFour = []
        self.ListMenuClicDroitRefFour = []
        self.ImgFournisseur = ImgInCanvas(self.CanvasMenu1.CanvasMenu, 'Datas/Fournisseurs/Logos/NC', 0.4, tk.CENTER,
                                          int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.5),
                                          int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.71))
        ChangeCursor(self.ImgFournisseur.CanvasImg)
        self.ImgFournisseur.CanvasImg.bind('<ButtonRelease-1>', self.ChargeFournisseur)
        self.ListRefFour.append(self.ImgFournisseur.CanvasImg)
        self.ListMenuClicDroitRefFour.append(tk.Menu(self.ImgFournisseur.CanvasImg, tearoff=0))
        self.ListMenuClicDroitRefFour[0].add_command(label="Recherche internet", command=self.ChercheWebFour)

        self.CanvasEtiqPrix = CanvasInWindow('Media/FrmInfo/Etiq/', self.RatioX * 0.9, self.RatioY * 0.7,
                                             self.CanvasMenu1.CanvasMenu, tk.CENTER,
                                             int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.5),
                                             int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.88), 0)
        self.ListRefFour.append(self.CanvasEtiqPrix.CanvasListIma)
        self.ListMenuClicDroitRefFour.append(tk.Menu(self.CanvasEtiqPrix.CanvasListIma, tearoff=0))
        self.ListMenuClicDroitRefFour[1].add_command(label="Recherche internet", command=self.ChercheWebFour)

        self.EtiqPrixNomProd = self.CanvasEtiqPrix.CanvasListIma.create_text(
            int(self.CanvasEtiqPrix.wsize * 0.5), int(self.CanvasEtiqPrix.hsize * 0.2),
            text=self.EntryNom.EntryData.get(),
            font=AppliFont('Helvetica', self.MainAppli.SizeFont - 1, 'bold', 0), anchor=tk.CENTER)

        self.CanvasEtiqPrix.CanvasListIma.create_text(
            int(self.CanvasEtiqPrix.wsize * 0.1), int(self.CanvasEtiqPrix.hsize * 0.45), text='Ref: ',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0), anchor=tk.W)

        self.Ref = EntryData(self.CanvasEtiqPrix.CanvasListIma, int(self.CanvasEtiqPrix.wsize * 0.05),
                             int(self.CanvasEtiqPrix.wsize * 0.2), int(self.CanvasEtiqPrix.hsize * 0.45),
                             tk.W, AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
        self.ListRefFour.append(self.Ref.EntryData)
        self.ListMenuClicDroitRefFour.append(tk.Menu(self.Ref.EntryData, tearoff=0))
        self.ListMenuClicDroitRefFour[2].add_command(label="Recherche internet", command=self.ChercheWebFour)

        self.Cdt = EntryData(self.CanvasEtiqPrix.CanvasListIma, int(self.CanvasEtiqPrix.wsize * 0.05),
                             int(self.CanvasEtiqPrix.wsize * 0.2), int(self.CanvasEtiqPrix.hsize * 0.6),
                             tk.W, AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
        self.ListRefFour.append(self.Cdt.EntryData)
        self.ListMenuClicDroitRefFour.append(tk.Menu(self.Cdt.EntryData, tearoff=0))
        self.ListMenuClicDroitRefFour[3].add_command(label="Recherche internet", command=self.ChercheWebFour)

        self.TextCdt = self.CanvasEtiqPrix.CanvasListIma.create_text(
            int(self.CanvasEtiqPrix.wsize * 0.1), int(self.CanvasEtiqPrix.hsize * 0.6),
            text='Cdt :', font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0), anchor=tk.W)

        self.PrixHT = EntryData(self.CanvasEtiqPrix.CanvasListIma, int(self.CanvasEtiqPrix.wsize * 0.025),
                                int(self.CanvasEtiqPrix.wsize * 0.73), int(self.CanvasEtiqPrix.hsize * 0.55),
                                tk.CENTER, AppliFont('Helvetica', self.MainAppli.SizeFont + 3, 'bold', 0))
        self.PrixHT.Data.set('PRIX')
        self.PrixHT.EntryData.config(justify='center')
        self.ListRefFour.append(self.PrixHT.EntryData)
        self.ListMenuClicDroitRefFour.append(tk.Menu(self.PrixHT.EntryData, tearoff=0))
        self.ListMenuClicDroitRefFour[4].add_command(label="Recherche internet", command=self.ChercheWebFour)

        self.CanvasEtiqPrix.CanvasListIma.create_text(
            int(self.CanvasEtiqPrix.wsize * 0.86), int(self.CanvasEtiqPrix.hsize * 0.55),
            text='€ HT', font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0), anchor=tk.W)

        for i in range(len(self.ListRefFour)):
            def GestEvt2(evt, j=i):
                return self.AffichMenuClicDroitRefFour(evt, j)

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

        self.CanvasMenu3 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.43),
                                      int(self.SY * 0.967), int(self.SX * 0.5), int(self.SY * 0.03), tk.N)

        self.ImgSousMenu3 = []
        self.ImgSousMenu3 = RedimImg(int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.97),
                                     int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.9), 'Media/FrmAjout/SousMenu/')
        self.CanvasSousMenu3 = CanvasApp(self, width=int(self.CanvasMenu3.CanvasMenu['width']) * 0.95,
                                         height=int(self.CanvasMenu3.CanvasMenu['height']) * 0.9)
        self.CanvasMenu3.CanvasMenu.create_window(int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.5),
                                                  int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.53),
                                                  anchor=tk.CENTER,
                                                  window=self.CanvasSousMenu3)
        self.ImgCanvasSousMenu3 = self.CanvasSousMenu3.create_image(0, 0, anchor=tk.NW, image=self.ImgSousMenu3[0])

        LabelInCanvas(self.CanvasMenu3.CanvasMenu, 'Documentation', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.005), tk.NW)

        self.NoPDF = NoPDF(self.CanvasSousMenu3, 'Media/FrmAjout/NoPDF/NoPDF2.jpg',
                           int(int(self.CanvasSousMenu3['width']) * 0.5),
                           int(int(self.CanvasSousMenu3['height']) * 0.5),
                           self.RatioX, self.RatioY)
        ChangeCursor(self.NoPDF.CanvasImgNoPdf)
        self.NoPDF.CanvasImgNoPdf.bind('<ButtonRelease-1>', self.ChargePDF)
        self.MenuClicDroitPDF = tk.Menu(self.NoPDF.CanvasImgNoPdf, tearoff=0)
        self.MenuClicDroitPDF.add_command(label="Recherche internet", command=self.CherchePDF)
        self.NoPDF.CanvasImgNoPdf.bind("<Button-3>", self.AffichMenuClicDroitPDF)

        self.BtnImportPDF = BtnAction(self.CanvasMenu3.CanvasMenu,
                                      int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.91),
                                      int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.06), self.RatioX,
                                      self.RatioY, 'Media/FrmAjout/BtnPDF/')
        self.BtnSuppPDF = BtnAction(self.CanvasMenu3.CanvasMenu, int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.96),
                                    int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.06), self.RatioX,
                                    self.RatioY, 'Media/FrmAjout/BtnSupp/')

        self.BtnImportPDF.CanvasBtn.bind('<ButtonRelease-1>', self.ChargePDF)
        self.BtnSuppPDF.CanvasBtn.bind('<ButtonRelease-1>', self.SupPDF)

        self.CanvasMenu2 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.282),
                                      int(self.SY * 0.967), int(self.SX * 0.998), int(self.SY * 0.03), tk.NE)

        LabelInCanvas(self.CanvasMenu2.CanvasMenu, 'Descriptif du matériel', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.005), tk.NW)
        self.ListDescript = []
        self.ListMenuClicDroitDescript = []
        NDescript = 0
        self.CanvasDescript = CanvasInWindow('Media/FrmInfo/FondDescriptMat/', self.RatioX * 1.65, self.RatioY * 1.65,
                                             self.CanvasMenu2.CanvasMenu, tk.CENTER,
                                             int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                                             int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.5), 0)
        self.ListDescript.append(self.CanvasDescript.CanvasListIma)
        self.ListMenuClicDroitDescript.append(tk.Menu(self.CanvasDescript.CanvasListIma, tearoff=0))
        self.ListMenuClicDroitDescript[NDescript].add_command(label="Recherche internet",
                                                              command=self.DescriptChercheWeb)
        NDescript += 1

        self.NomMat = self.CanvasDescript.CanvasListIma.create_text(
            int(self.CanvasDescript.wsize * 0.5), int(self.CanvasDescript.hsize * 0.08), text=self.EntryNom.Data.get(),
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 1), anchor=tk.CENTER)

        self.CanvasVisuel = CanvasInWindow('Media/FrmAjout/NoVisuel/', self.RatioX, self.RatioY,
                                           self.CanvasMenu2.CanvasMenu, tk.CENTER,
                                           int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                                           int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.3), 0)
        self.ListDescript.append(self.CanvasVisuel.CanvasListIma)
        self.ListMenuClicDroitDescript.append(tk.Menu(self.CanvasVisuel.CanvasListIma, tearoff=0))
        self.ListMenuClicDroitDescript[NDescript].add_command(label="Recherche internet",
                                                              command=self.DescriptChercheWeb)
        self.ListMenuClicDroitDescript[NDescript].add_separator()
        self.ListMenuClicDroitDescript[NDescript].add_command(label="Coller une image", command=self.ColleVisuel)
        NDescript += 1

        ChangeCursor(self.CanvasVisuel.CanvasListIma)
        self.CanvasVisuel.CanvasListIma.bind('<ButtonRelease-1>', self.ChargeVisuel)

        self.CanvasDescript.CanvasListIma.create_text(
            int(self.CanvasDescript.wsize * 0.05), int(self.CanvasDescript.hsize * 0.44), text='Caractéristiques:',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 1), anchor=tk.W)

        LabelInCanvas(self.CanvasDescript.CanvasListIma, 'Type', '#C0C0C0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0),
                      int(self.CanvasDescript.wsize * 0.25), int(self.CanvasDescript.hsize * 0.5), tk.CENTER)
        LabelInCanvas(self.CanvasDescript.CanvasListIma, 'Valeur', '#C0C0C0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0),
                      int(self.CanvasDescript.wsize * 0.75), int(self.CanvasDescript.hsize * 0.5), tk.CENTER)

        self.ListCaractType = []
        self.ListCaractVal = []
        for i in range(4):
            self.ListCaractType.append(
                EntryData(self.CanvasDescript.CanvasListIma, int(self.CanvasDescript.wsize * 0.05),
                          int(self.CanvasDescript.wsize * 0.25),
                          int(self.CanvasDescript.hsize * 0.55 + i * self.CanvasDescript.hsize * 0.05),
                          tk.CENTER, AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0)))
            self.ListDescript.append(self.ListCaractType[i].EntryData)
            self.ListMenuClicDroitDescript.append(tk.Menu(self.ListCaractType[i].EntryData, tearoff=0))
            self.ListMenuClicDroitDescript[NDescript].add_command(label="Recherche internet",
                                                                  command=self.DescriptChercheWeb)
            NDescript += 1

            self.ListCaractVal.append(
                EntryData(self.CanvasDescript.CanvasListIma, int(self.CanvasDescript.wsize * 0.05),
                          int(self.CanvasDescript.wsize * 0.75),
                          int(
                              self.CanvasDescript.hsize * 0.55 + i * self.CanvasDescript.hsize * 0.05),
                          tk.CENTER, AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0)))
            self.ListDescript.append(self.ListCaractVal[i].EntryData)
            self.ListMenuClicDroitDescript.append(tk.Menu(self.ListCaractVal[i].EntryData, tearoff=0))
            self.ListMenuClicDroitDescript[NDescript].add_command(label="Recherche internet",
                                                                  command=self.DescriptChercheWeb)
            NDescript += 1

        self.CanvasDescript.CanvasListIma.create_text(
            int(self.CanvasDescript.wsize * 0.05), int(self.CanvasDescript.hsize * 0.76), text='Descriptif:',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 1), anchor=tk.W)

        self.ZoneText = ZoneScrolledText(self.CanvasDescript.CanvasListIma, width=int(self.CanvasDescript.wsize * 0.12),
                                         height=int(self.CanvasDescript.hsize * 0.01),
                                         font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0))
        self.CanvasDescript.CanvasListIma.create_window(int(self.CanvasDescript.wsize * 0.025),
                                                        int(self.CanvasDescript.hsize * 0.79), anchor=tk.NW,
                                                        window=self.ZoneText)
        self.ListDescript.append(self.ZoneText)
        self.ListMenuClicDroitDescript.append(tk.Menu(self.ZoneText, tearoff=0))
        self.ListMenuClicDroitDescript[NDescript].add_command(label="Recherche internet",
                                                              command=self.DescriptChercheWeb)

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

            self.ListDescript[i].bind("<Button-3>", GestEvt)

        self.BtnOK = BtnAction(self.CanvasFrmFond, int(self.SX * 0.962), int(self.SY * 0.972), 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.972), 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.SaveNewMat)

        if self.MainAppli.NAction != 203:
            self.AffichInfoMat()
            self.TextAction = 'Mise à jour - Matériel - '
        else:
            self.TextAction = 'Ajout - Matériel - '

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

        self.CanvasFrmFond.pack()

    def ModifNom(self, _):
        self.CanvasEtiqPrix.CanvasListIma.itemconfig(self.EtiqPrixNomProd, text=self.EntryNom.EntryData.get())
        self.CanvasDescript.CanvasListIma.itemconfig(self.NomMat, text=self.EntryNom.EntryData.get())
        if self.EntryNom.EntryData.get() != self.NomInit:
            self.ActionModifNom = True
        else:
            self.ActionModifNom = False

    def ModifCat(self, _):
        Cat = []
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute('SELECT CATEGORIE'
                                       ' FROM MATERIEL WHERE CATEGORIE LIKE \"%' + self.EntryCatMat.EntryData.get() +
                                       '%\" order by CATEGORIE')
            Cat = self.MainAppli.cur.fetchall()
        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute('SELECT CATEGORIE'
                                           ' FROM MATERIEL WHERE CATEGORIE LIKE \"%' +
                                           self.EntryCatMat.EntryData.get() + '%\" order by CATEGORIE')
            Cat = self.MainAppli.curphys.fetchall()
        if len(Cat) > 0:
            self.EntryCatMat.Data.set(Cat[0][0])

    def CalculQTot(self, _):
        self.QTotal = 0
        try:
            self.ActionQTot()
            self.CanvasBoite.CanvasListIma.itemconfig(self.QTot, text=str(self.QTotal))
        except:
            self.CanvasBoite.CanvasListIma.itemconfig(self.QTot, text=str(self.QTotal))

    def ActionQTot(self):
        self.QTotal = 0
        if self.EntryQuantLabo.EntryData.get() != '':
            self.QTotal = self.QTotal + int(self.EntryQuantLabo.EntryData.get())
        if self.EntryQuantTP.EntryData.get() != '':
            self.QTotal = self.QTotal + int(self.EntryQuantTP.EntryData.get())
        if self.EntryQuantSpectro.EntryData.get() != '':
            self.QTotal = self.QTotal + int(self.EntryQuantSpectro.EntryData.get())
        if self.MainAppli.BaseEnCours == "CHIMIE":
            if self.EntryQuantLabo2.EntryData.get() != '':
                self.QTotal = self.QTotal + int(self.EntryQuantLabo2.EntryData.get())
            if self.EntryQuantTP2.EntryData.get() != '':
                self.QTotal = self.QTotal + int(self.EntryQuantTP2.EntryData.get())

    def ChargeFournisseur(self, _):
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("select " + self.MainAppli.ListChampsTabFournisseurs +
                                       " from Fournisseurs order by NOM")
            self.ListFours = self.MainAppli.cur.fetchall()
        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("select " + self.MainAppli.ListChampsTabFournisseurs +
                                           " from Fournisseurs order by NOM")
            self.ListFours = self.MainAppli.curphys.fetchall()
        self.FrmModifFour = FrmModifFour(self.CanvasFrmFond, self.RatioX, self.RatioY, self.ListFours, 1, self)

    def AffichLogoFour(self, Four):
        Logo = []
        if Four is not None and Four != '':
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.MainAppli.cur.execute('SELECT Logo'
                                           ' FROM Fournisseurs WHERE NOM LIKE \'%' + Four + '%\' order by NOM')
                Logo = self.MainAppli.cur.fetchall()
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.MainAppli.curphys.execute('SELECT Logo'
                                               ' FROM Fournisseurs WHERE NOM LIKE \'%' + Four + '%\' order by NOM')
                Logo = self.MainAppli.curphys.fetchall()
        if len(Logo) > 0 and Logo[0][0] != '' and Logo[0][0] is not None:
            PathLogo = 'Datas/Fournisseurs/Logos/' + Logo[0][0]
            self.Fournisseur = Logo[0][0]
        else:
            if Four is None or Four == '':
                PathLogo = 'Datas/Fournisseurs/Logos/NC'
                self.Fournisseur = ''
            else:
                PathLogo = 'Datas/Fournisseurs/Logos/Vide'
                self.Fournisseur = Four
        self.ImgFournisseur.CanvasImg.destroy()
        self.ImgFournisseur = ImgInCanvas(self.CanvasMenu1.CanvasMenu, PathLogo, 0.4,
                                          tk.CENTER, int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.5),
                                          int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.71))
        ChangeCursor(self.ImgFournisseur.CanvasImg)
        self.ImgFournisseur.CanvasImg.bind('<ButtonRelease-1>', self.ChargeFournisseur)
        self.ListRefFour[0] = self.ImgFournisseur.CanvasImg
        self.ListMenuClicDroitRefFour[0] = tk.Menu(self.ImgFournisseur.CanvasImg, tearoff=0)
        self.ListMenuClicDroitRefFour[0].add_command(label="Recherche internet", command=self.ChercheWebFour)

        def GestEvt(evt, j=0):
            return self.AffichMenuClicDroitRefFour(evt, j)

        self.ListRefFour[0].bind("<Button-3>", GestEvt)

        if (len(Logo) == 0 or Logo[0][0] == '' or Logo[0][0] is None) and self.Fournisseur != '':
            if len(self.Fournisseur) < 15:
                TextFournisseur = self.Fournisseur
            else:
                TextFournisseur = self.Fournisseur.split(' ')[0]
                for i in range(1, len(self.Fournisseur.split(' '))):
                    TextFournisseur = TextFournisseur + '\n' + self.Fournisseur.split(' ')[i]
            self.ImgFournisseur.CanvasImg.create_text(int(int(self.ImgFournisseur.CanvasImg['width']) * 0.5),
                                                      int(int(self.ImgFournisseur.CanvasImg['height']) * 0.5),
                                                      text=TextFournisseur,
                                                      font=AppliFont('Helvetica', self.MainAppli.SizeFont + 4, 'bold',
                                                                     0), anchor=tk.CENTER, justify=tk.CENTER)

    def ChargeVisuel(self, _):
        self.PathFilejpgToOpen = ''
        self.PathFilejpgToOpen = tkfiledialog.askopenfilename(title="Ouvrir un fichier",
                                                              filetypes=[('JPG files', '*.*')], parent=self)
        if self.PathFilejpgToOpen != '':
            self.AffichVisuel(self.PathFilejpgToOpen)
            self.AjoutVisuelBoite()

        self.lift()

    def ChargePDF(self, _):
        self.PathFilePDFToOpen = tkfiledialog.askopenfilename(title="Ouvrir un fichier",
                                                              filetypes=[('PDF files', '.pdf')], parent=self)
        if self.PathFilePDFToOpen != '':
            self.FrmPDF = FrmPDF(self.CanvasSousMenu3, self.PathFilePDFToOpen, 1.3,
                                 int(self.CanvasMenu3.CanvasMenu['height']),
                                 int(int(self.CanvasSousMenu3['width']) * 0.5),
                                 int(int(self.CanvasSousMenu3['height']) * 0.48),
                                 int(int(self.CanvasSousMenu3['width']) * 0.98),
                                 int(int(self.CanvasSousMenu3['height']) * 0.9))
            self.FrmPDF.CanvasDoc.bind('<Double-1>', self.OuvrePDF)
            self.MenuClicDroitPDF = tk.Menu(self.FrmPDF.CanvasDoc, tearoff=0)
            self.MenuClicDroitPDF.add_command(label="Recherche internet", command=self.CherchePDF)
            self.MenuClicDroitPDF.add_separator()
            self.MenuClicDroitPDF.add_command(label="Supprimer le document", command=self.ActionSupPDF)
            self.FrmPDF.CanvasDoc.bind("<Button-3>", self.AffichMenuClicDroitPDF)
            self.DocPDF = True

        self.lift(self.parent)

    def SupPDF(self, _):
        self.ActionSupPDF()

    def ActionSupPDF(self):
        self.BtnSuppPDF.CanvasBtn.itemconfig(self.BtnSuppPDF.ImgCanvasBtn, image=self.BtnSuppPDF.ImgBtn[0])
        if self.DocPDF:
            for widget in self.FrmPDF.Container.winfo_children():
                widget.destroy()
            self.FrmPDF.CanvasScale.destroy()
            self.NoPDF = NoPDF(self.CanvasSousMenu3, 'Media/FrmAjout/NoPDF/NoPDF2.jpg',
                               int(int(self.CanvasSousMenu3['width']) * 0.5),
                               int(int(self.CanvasSousMenu3['height']) * 0.5),
                               self.RatioX, self.RatioY)
            ChangeCursor(self.NoPDF.CanvasImgNoPdf)
            self.NoPDF.CanvasImgNoPdf.bind('<ButtonRelease-1>', self.ChargePDF)
            self.MenuClicDroitPDF = tk.Menu(self.NoPDF.CanvasImgNoPdf, tearoff=0)
            self.MenuClicDroitPDF.add_command(label="Recherche internet", command=self.CherchePDF)
            self.NoPDF.CanvasImgNoPdf.bind("<Button-3>", self.AffichMenuClicDroitPDF)
            self.DocPDF = False
            self.Notice = ''

    def OuvrePDF(self, _):
        if self.PathFilePDFToOpen == '':
            if self.MainAppli.BaseEnCours == "CHIMIE":
                AffichPDF(self.EntryNom.EntryData.get() + ' - Notice', 'Datas/NoticeChim/' + self.Notice + '.pdf',
                          self)
            elif self.MainAppli.BaseEnCours == "PHYS":
                AffichPDF(self.EntryNom.EntryData.get() + ' - Notice', 'Datas/NoticePhys/' + self.Notice + '.pdf',
                          self)
        else:
            AffichPDF(self.EntryNom.EntryData.get() + ' - Notice', self.PathFilePDFToOpen, self)

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

    def SaveNewMat(self, _):
        if self.EntryNom.EntryData.get() != '':
            NOcur = 0
            Rep = True
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.MainAppli.cur.execute("Select * from MATERIEL where " + 'NOMS = "' +
                                           self.EntryNom.EntryData.get() + '"')
                NOcur = len(self.MainAppli.cur.fetchall())
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.MainAppli.curphys.execute("Select * from MATERIEL where " + 'NOMS = "' +
                                               self.EntryNom.EntryData.get() + '"')
                NOcur = len(self.MainAppli.curphys.fetchall())

            if NOcur > 0:
                Rep = tkMB.askyesno('Attention', 'Un matériel nommé "' + self.EntryNom.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 MATERIEL WHERE " + 'NOMS = "' + self.EntryNom.EntryData.get() + '"'
                    if self.MainAppli.BaseEnCours == "CHIMIE":
                        self.MainAppli.cur.execute(SQLRequet)
                        self.MainAppli.DataBaseChimie.commit()
                    elif self.MainAppli.BaseEnCours == "PHYS":
                        self.MainAppli.curphys.execute(SQLRequet)
                        self.MainAppli.DataBasePhys.commit()

                Nom = self.EntryNom.EntryData.get()
                NomSave = ModifString(self.EntryNom.EntryData.get())
                LNoms = []
                if self.MainAppli.BaseEnCours == "CHIMIE":
                    self.MainAppli.cur.execute("Select NOMS from MATERIEL")
                    LNoms = self.MainAppli.cur.fetchall()
                elif self.MainAppli.BaseEnCours == "PHYS":
                    self.MainAppli.curphys.execute("Select NOMS from MATERIEL")
                    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()))

                if self.PathFilejpgToOpen != '':
                    Visuel = NomSave
                    if self.MainAppli.BaseEnCours == "CHIMIE":
                        shutil.copy(self.PathFilejpgToOpen, 'Datas/VisuelMatChim/' + Visuel)
                    elif self.MainAppli.BaseEnCours == "PHYS":
                        shutil.copy(self.PathFilejpgToOpen, 'Datas/VisuelMatPhys/' + Visuel)
                elif self.ActionModifNom:
                    if self.Visuel != '':
                        Visuel = NomSave
                        if self.MainAppli.BaseEnCours == "CHIMIE":
                            if not os.path.exists('Datas/VisuelMatChim/' + Visuel):
                                shutil.copy('Datas/VisuelMatChim/' + self.Visuel, 'Datas/VisuelMatChim/' + Visuel)
                        elif self.MainAppli.BaseEnCours == "PHYS":
                            if not os.path.exists('Datas/VisuelMatPhys/' + Visuel):
                                shutil.copy('Datas/VisuelMatPhys/' + self.Visuel, 'Datas/VisuelMatPhys/' + Visuel)
                    else:
                        Visuel = self.Visuel
                else:
                    Visuel = self.Visuel
                cat = self.EntryCatMat.EntryData.get()
                LaboLieu = self.EntryLieuLabo.EntryData.get()
                LaboQuant = self.EntryQuantLabo.EntryData.get()
                SalleTPLieu = self.EntryLieuTP.EntryData.get()
                SalleTPQuant = self.EntryQuantTP.EntryData.get()
                SpectroLieu = self.EntryLieuSpectro.EntryData.get()
                SpectroQuant = self.EntryQuantSpectro.EntryData.get()
                if self.MainAppli.BaseEnCours == "CHIMIE":
                    LaboLieu2 = self.EntryLieuLabo2.EntryData.get()
                    LaboQuant2 = self.EntryQuantLabo2.EntryData.get()
                    PosteTPLieu = self.EntryLieuTP2.EntryData.get()
                    PosteTPQuant = self.EntryQuantTP2.EntryData.get()
                    QStock = str(self.QTotal)
                else:
                    LaboLieu2 = ''
                    LaboQuant2 = ''
                    PosteTPLieu = ''
                    PosteTPQuant = ''
                    QStock = ''
                Qutil = self.EntryQuantMin.EntryData.get()
                if self.PathFileFournisseurToOpen != '':
                    Fournisseur = Path(self.PathFileFournisseurToOpen).stem
                else:
                    Fournisseur = self.Fournisseur
                ref = self.Ref.EntryData.get()
                Cdt = self.Cdt.EntryData.get()
                PHT = self.PrixHT.EntryData.get()
                ListCaractType = []
                ListCaractVal = []
                for i in range(4):
                    ListCaractType.append(self.ListCaractType[i].EntryData.get())
                    ListCaractVal.append(self.ListCaractVal[i].EntryData.get())

                rep = ''
                rep2 = ''
                if self.MainAppli.BaseEnCours == 'CHIMIE':
                    rep = 'NoticeChim'
                    rep2 = 'DescriptMatChim'
                elif self.MainAppli.BaseEnCours == 'PHYS':
                    rep = 'NoticePhys'
                    rep2 = 'DescriptMatPhys'

                if self.PathFilePDFToOpen != '':
                    Notice = NomSave
                    shutil.copy(self.PathFilePDFToOpen, 'Datas/' + rep + '/' + Notice + '.pdf')
                elif self.ActionModifNom:
                    if self.Notice != '':
                        Notice = NomSave
                        if not os.path.exists('Datas/' + rep + '/' + Notice + '.pdf'):
                            shutil.copy('Datas/' + rep + '/' + self.Notice + '.pdf',
                                        'Datas/' + rep + '/' + Notice + '.pdf')
                    else:
                        Notice = self.Notice
                else:
                    Notice = self.Notice

                Descript = self.ZoneText.get(0.0, tk.END)
                SaveDescript = False
                for i in range(len(Descript)):
                    if Descript[i] != '' and Descript[i] != ' ' and Descript[i] != '\n':
                        SaveDescript = True
                        break
                FileDescript = ''
                if SaveDescript:
                    FileDescript = NomSave
                    File = open('Datas/' + rep2 + '/' + FileDescript + '.txt', "w", encoding="utf-8")
                    File.write(Descript)
                    File.close()
                else:
                    if os.path.exists('Datas/' + rep2 + '/' + self.FileDescriptInit + '.txt'):
                        os.remove('Datas/' + rep2 + '/' + self.FileDescriptInit + '.txt')

                if self.MainAppli.BaseEnCours == "CHIMIE":
                    data = [(Nom, Visuel, cat, LaboLieu, LaboQuant, LaboLieu2, LaboQuant2, SalleTPLieu, SalleTPQuant,
                             PosteTPLieu, PosteTPQuant, SpectroLieu, SpectroQuant, QStock, Qutil, Fournisseur, ref, Cdt,
                             PHT, ListCaractType[0], ListCaractVal[0], ListCaractType[1], ListCaractVal[1],
                             ListCaractType[2], ListCaractVal[2], ListCaractType[3], ListCaractVal[3], Notice,
                             FileDescript, self.QCOM, self.QCOMANNUL, self.QENCOM)]
                    self.MainAppli.cur.execute(
                        "INSERT INTO MATERIEL(" + self.MainAppli.ListChampsTabMat + ") VALUES(?,?,?,?,?,?,?,?,?,?,?,?,"
                                                                                    "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,"
                                                                                    "?,?,?,?)", data[0])

                    self.MainAppli.DataBaseChimie.commit()
                    self.MainAppli.SaveListModifDTB('Chimie', self.TextAction + Nom)
                    self.MainAppli.cur.execute("select " + self.MainAppli.ListChampsTabMat +
                                               " from MATERIEL order by NOMS")
                    self.MainAppli.ListMats = self.MainAppli.cur.fetchall()
                elif self.MainAppli.BaseEnCours == "PHYS":
                    data = [(Nom, Visuel, cat, LaboLieu, LaboQuant, SalleTPLieu, SalleTPQuant,
                             SpectroLieu, SpectroQuant, Qutil, Fournisseur, ref, Cdt,
                             PHT, ListCaractType[0], ListCaractVal[0], ListCaractType[1], ListCaractVal[1],
                             ListCaractType[2], ListCaractVal[2], ListCaractType[3], ListCaractVal[3], Notice,
                             FileDescript, self.QCOM, self.QCOMANNUL, self.QENCOM)]
                    self.MainAppli.curphys.execute(
                        "INSERT INTO MATERIEL(" + self.MainAppli.ListChampsTabMatPhys + ") VALUES(?,?,?,?,?,?,?,?,"
                                                                                        "?,?,?,?,?,?,?,?,?,?,?,?,?,?,"
                                                                                        "?,?,?,?,?)", data[0])

                    self.MainAppli.DataBasePhys.commit()
                    self.MainAppli.SaveListModifDTB('Physique', self.TextAction + Nom)
                    self.MainAppli.curphys.execute("select " + self.MainAppli.ListChampsTabMatPhys +
                                                   " from MATERIEL order by NOMS")
                    self.MainAppli.ListMats = self.MainAppli.curphys.fetchall()

                if Visuel != self.VisuelInit and not self.ActionModifNom and self.VisuelInit != '':
                    if self.MainAppli.BaseEnCours == "CHIMIE":
                        if os.path.exists('Datas/VisuelMatChim/' + self.VisuelInit):
                            os.remove('Datas/VisuelMatChim/' + self.VisuelInit)
                    elif self.MainAppli.BaseEnCours == "PHYS":
                        if os.path.exists('Datas/VisuelMatPhys/' + self.VisuelInit):
                            os.remove('Datas/VisuelMatPhys/' + self.VisuelInit)

                if Notice != self.NoticeInit and not self.ActionModifNom and self.NoticeInit != '':
                    if os.path.exists('Datas/' + rep + '/' + self.NoticeInit + '.pdf'):
                        os.remove('Datas/' + rep + '/' + self.NoticeInit + '.pdf')

                if FileDescript != self.FileDescriptInit and not self.ActionModifNom and self.FileDescriptInit != '':
                    if os.path.exists('Datas/' + rep2 + '/' + self.FileDescriptInit + '.txt'):
                        os.remove('Datas/' + rep2 + '/' + self.FileDescriptInit + '.txt')

                if self.MainAppli.NAction == 204:
                    if self.MainAppli.OldNAction == 2:
                        self.MainAppli.ChargeListProduits(self.MainAppli.ListMats)
                        self.MainAppli.AffichEtagProduits(self.MainAppli.ListMats)
                    elif self.MainAppli.OldNAction == 2011:
                        self.MainAppli.NAction = 201
                        self.MainAppli.ActionRecherche()
                    elif self.MainAppli.OldNAction == 2022:
                        self.MainAppli.AffichListMatCat(self.MainAppli.NSCatselected)
                else:
                    self.MainAppli.ChargeListProduits(self.MainAppli.ListMats)
                    self.MainAppli.AffichEtagProduits(self.MainAppli.ListMats)

                try:
                    self.MainAppli.IndexElt = self.MainAppli.ListNomProd.index(Nom)
                    NEtag = CalculNEtag(self.MainAppli.IndexElt + 1, 12)
                    self.MainAppli.NEtag = NEtag
                    self.MainAppli.EtagMat.DefilMat.set(NEtag)
                    if NEtag == 0:
                        self.MainAppli.EtagMat.SelectMat(self.MainAppli.IndexElt)
                except:
                    pass
                self.CacheFrmAjout(_)
            else:
                self.lift()
        else:
            tkMB.showwarning('Attention', "Veuillez indiquer le nom du matériel!", parent=self)
            self.lift()

    def AffichVisuel(self, file):
        self.CanvasVisuel.CanvasListIma.destroy()
        self.ImgVisuelMat = []
        img = Image.open(file)
        imgEtiqwsize = int(self.CanvasDescript.wsize * 0.5)
        imgEtiqhsize = int(imgEtiqwsize * float(img.size[1]) / float(img.size[0]))
        if imgEtiqhsize > self.CanvasDescript.hsize * 0.25:
            imgEtiqhsize = int(self.CanvasDescript.hsize * 0.25)
            imgEtiqwsize = int(imgEtiqhsize * float(img.size[0]) / float(img.size[1]))
        img = img.resize((imgEtiqwsize, imgEtiqhsize), Image.ANTIALIAS)
        self.ImgVisuelMat.append(ImageTk.PhotoImage(img))
        self.img = img

        if self.CanvasContVisuelMat is not None:
            self.CanvasContVisuelMat.destroy()
        self.CanvasContVisuelMat = CanvasApp(self.CanvasDescript.CanvasListIma, width=imgEtiqwsize, height=imgEtiqhsize)
        self.CanvasDescript.CanvasListIma.create_window(int(self.CanvasDescript.wsize * 0.5),
                                                        int(self.CanvasDescript.hsize * 0.25), anchor=tk.CENTER,
                                                        window=self.CanvasContVisuelMat)
        self.ImgCanvasContVisuelMat = self.CanvasContVisuelMat.create_image(0, 0, anchor=tk.NW,
                                                                            image=self.ImgVisuelMat[0])
        ChangeCursor(self.CanvasContVisuelMat)
        self.CanvasContVisuelMat.bind('<ButtonRelease-1>', self.ChargeVisuel)

        self.MenuClicDroitVisuelMat = tk.Menu(self.CanvasContVisuelMat, tearoff=0)
        self.MenuClicDroitVisuelMat.add_command(label="Effacer", command=self.EffacerVisuelMat)
        self.CanvasContVisuelMat.bind("<Button-3>", self.AffichMenuClicDroitVisuelMat)

    def AjoutVisuelBoite(self):
        self.ImgEtiqMat = []
        img = self.img
        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)

    def AffichMenuClicDroitVisuelMat(self, event):
        self.MenuClicDroitVisuelMat.post(event.x_root, event.y_root)

    def AffichMenuClicDroitRefFour(self, event, j):
        self.ListMenuClicDroitRefFour[j].post(event.x_root, event.y_root)
        self.NRefFour = j

    def EffacerVisuelMat(self):
        self.CanvasContVisuelMat.destroy()
        self.CanvasVisuel = CanvasInWindow('Media/FrmAjout/NoVisuel/', self.RatioX, self.RatioY,
                                           self.CanvasMenu2.CanvasMenu, tk.CENTER,
                                           int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                                           int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.3), 0)
        ChangeCursor(self.CanvasVisuel.CanvasListIma)
        self.CanvasVisuel.CanvasListIma.bind('<ButtonRelease-1>', self.ChargeVisuel)
        self.ListDescript[1] = self.CanvasVisuel.CanvasListIma
        self.ListMenuClicDroitDescript[1] = tk.Menu(self.CanvasVisuel.CanvasListIma, tearoff=0)
        self.ListMenuClicDroitDescript[1].add_command(label="Recherche internet", command=self.DescriptChercheWeb)
        self.ListMenuClicDroitDescript[1].add_separator()
        self.ListMenuClicDroitDescript[1].add_command(label="Coller une image", command=self.ColleVisuel)
        self.CanvasVisuel.CanvasListIma.bind('<ButtonRelease-1>', self.ChargeVisuel)

        def GestEvt(evt, j=1):
            return self.AffichMenuClicDroitDescript(evt, j)

        self.ListDescript[1].bind("<Button-3>", GestEvt)

        self.CanvasImgEtiqMat.destroy()
        for i in range(1, 5):
            self.CanvasBoite.CanvasListIma.delete('Line' + str(i))
        self.Visuel = ''

    def DescriptChercheWeb(self):
        CaractList = ['Descriptif', 'Visuel', 'Caractéristiques', 'Caractéristiques', 'Caractéristiques',
                      'Caractéristiques', 'Caractéristiques', 'Caractéristiques', 'Caractéristiques',
                      'Caractéristiques', 'Descriptif']
        webbrowser.open('https://www.google.fr/search?q=' + CaractList[self.NDescript] + ' - ' +
                        self.EntryNom.EntryData.get(), new=1)

    def CherchePDF(self):
        webbrowser.open('https://www.google.fr/search?q=Notice - ' + self.EntryNom.EntryData.get(), new=1)

    def ChercheWebFour(self):
        RefFourList = ['Fournisseur', 'Fournisseur', 'Référence', 'Conditionnement', 'Prix']
        if self.Fournisseur != '':
            if self.NRefFour < 2:
                webbrowser.open('https://www.google.fr/search?q=' + self.Fournisseur + ' - ' +
                                self.EntryNom.EntryData.get(), new=1)
            else:
                webbrowser.open('https://www.google.fr/search?q=' + self.Fournisseur + ' - ' +
                                RefFourList[self.NRefFour] + ' - ' + self.EntryNom.EntryData.get(), new=1)
        else:
            webbrowser.open('https://www.google.fr/search?q=' + RefFourList[self.NRefFour] + ' - ' +
                            self.EntryNom.EntryData.get(), new=1)

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

    def AffichInfoMat(self):
        Mat = []
        if self.MainAppli.NAction == 2:
            Mat = self.MainAppli.ListMats[self.MainAppli.IndexElt]
        elif self.MainAppli.NAction == 2011:
            Mat = self.MainAppli.ListRecherch[self.MainAppli.IndexElt]
        elif self.MainAppli.NAction == 2022:
            Mat = self.MainAppli.ListMatCat[self.MainAppli.IndexElt]
        ChargeEntry(self.EntryNom, Mat[0])
        self.NomInit = Mat[0]
        self.CanvasEtiqPrix.CanvasListIma.itemconfig(self.EtiqPrixNomProd, text=self.EntryNom.EntryData.get())
        self.CanvasDescript.CanvasListIma.itemconfig(self.NomMat, text=self.EntryNom.EntryData.get())

        if Mat[1] is not None and Mat[1] != '':
            self.Visuel = Mat[1]
            self.VisuelInit = self.Visuel
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.AffichVisuel('Datas/VisuelMatChim/' + Mat[1])
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.AffichVisuel('Datas/VisuelMatPhys/' + Mat[1])
            self.AjoutVisuelBoite()
        if Mat[2] is not None and Mat[2] != '':
            self.EntryCatMat.Data.set(Mat[2])
        if Mat[3] is not None and Mat[3] != '':
            self.EntryLieuLabo.Data.set(Mat[3])
            self.EntryQuantLabo.Data.set(Mat[4])
        if Mat[5] is not None and Mat[5] != '' and self.MainAppli.BaseEnCours == "CHIMIE":
            self.EntryLieuLabo2.Data.set(Mat[5])
            self.EntryQuantLabo2.Data.set(Mat[6])
        IDep = 0
        if self.MainAppli.BaseEnCours == "CHIMIE":
            if Mat[7] is not None and Mat[7] != '':
                self.EntryLieuTP.Data.set(Mat[7])
                self.EntryQuantTP.Data.set(Mat[8])
            if Mat[9] is not None and Mat[9] != '':
                self.EntryLieuTP2.Data.set(Mat[9])
                self.EntryQuantTP2.Data.set(Mat[10])
            if Mat[11] is not None and Mat[11] != '':
                self.EntryLieuSpectro.Data.set(Mat[11])
                self.EntryQuantSpectro.Data.set(Mat[12])
            if Mat[13] is not None and Mat[13] != '':
                self.CanvasBoite.CanvasListIma.itemconfig(self.QTot, text=Mat[13])
                self.QTotal = int(Mat[13])
            IDep = 14
        elif self.MainAppli.BaseEnCours == "PHYS":
            if Mat[5] is not None and Mat[5] != '':
                self.EntryLieuTP.Data.set(Mat[5])
                self.EntryQuantTP.Data.set(Mat[6])
            if Mat[7] is not None and Mat[7] != '':
                self.EntryLieuSpectro.Data.set(Mat[7])
                self.EntryQuantSpectro.Data.set(Mat[8])
            self.ActionQTot()
            self.CanvasBoite.CanvasListIma.itemconfig(self.QTot, text=str(self.QTotal))
            IDep = 9

        if Mat[IDep] is not None and Mat[IDep] != '':
            self.EntryQuantMin.Data.set(Mat[IDep])
        self.AffichLogoFour(Mat[IDep + 1])
        if Mat[IDep + 2] is not None and Mat[IDep + 2] != '':
            self.Ref.Data.set(Mat[IDep + 2])
        if Mat[IDep + 3] is not None and Mat[IDep + 3] != '':
            self.Cdt.Data.set(Mat[IDep + 3])
        if Mat[IDep + 4] is not None and Mat[IDep + 4] != '':
            self.PrixHT.Data.set(Mat[IDep + 4])
        else:
            self.PrixHT.Data.set('')

        indice = 0
        indice2 = 0
        indice3 = 0
        indice4 = 0
        rep = ''
        rep2 = ''
        if self.MainAppli.BaseEnCours == 'CHIMIE':
            indice = 27
            indice2 = 19
            indice3 = 28
            indice4 = 29
            rep = 'NoticeChim'
            rep2 = 'DescriptMatChim'
        elif self.MainAppli.BaseEnCours == 'PHYS':
            indice = 22
            indice2 = 14
            indice3 = 23
            indice4 = 24
            rep = 'NoticePhys'
            rep2 = 'DescriptMatPhys'
        if Mat[indice] is not None and Mat[indice] != '' and \
                os.path.exists('Datas/' + rep + '/' + Mat[indice] + '.pdf'):
            self.FrmPDF = FrmPDF(self.CanvasSousMenu3, 'Datas/' + rep + '/' + Mat[indice] + '.pdf', 1.3,
                                 int(self.CanvasMenu3.CanvasMenu['height']),
                                 int(int(self.CanvasSousMenu3['width']) * 0.5),
                                 int(int(self.CanvasSousMenu3['height']) * 0.48),
                                 int(int(self.CanvasSousMenu3['width']) * 0.98),
                                 int(int(self.CanvasSousMenu3['height']) * 0.9))
            self.FrmPDF.CanvasDoc.bind('<Double-1>', self.OuvrePDF)
            self.MenuClicDroitPDF = tk.Menu(self.FrmPDF.CanvasDoc, tearoff=0)
            self.MenuClicDroitPDF.add_command(label="Recherche internet", command=self.CherchePDF)
            self.MenuClicDroitPDF.add_separator()
            self.MenuClicDroitPDF.add_command(label="Supprimer le document", command=self.ActionSupPDF)
            self.FrmPDF.CanvasDoc.bind("<Button-3>", self.AffichMenuClicDroitPDF)
            self.DocPDF = True
            self.Notice = Mat[indice]
            self.NoticeInit = self.Notice

        for i in range(0, 8, 2):
            if Mat[indice2 + i] is not None and Mat[indice2 + i] != '':
                self.ListCaractType[int(i / 2)].Data.set(Mat[indice2 + i])
                self.ListCaractVal[int(i / 2)].Data.set(Mat[indice2 + i + 1])

        if Mat[indice3] is not None and Mat[indice3] != '':
            self.FileDescriptInit = Mat[indice3]
            File = open('Datas/' + rep2 + '/' + Mat[indice3] + '.txt', "r", encoding="utf-8")
            for ligne in File:
                self.ZoneText.insert(tk.INSERT, ligne)

        if Mat[indice4] is not None and Mat[indice4] != '':
            self.QCOM = Mat[indice4]

        if Mat[indice4 + 1] is not None and Mat[indice4 + 1] != '':
            self.QCOMANNUL = Mat[indice4 + 1]

        if Mat[indice4 + 2] is not None and Mat[indice4 + 2] != '':
            self.QENCOM = Mat[indice4 + 2]

    def AffichMenuClicDroitDescript(self, event, j):
        self.ListMenuClicDroitDescript[j].post(event.x_root, event.y_root)
        self.NDescript = j

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

    def ColleVisuel(self):
        img = ImageGrab.grabclipboard()
        if img is not None:
            self.PathFilejpgToOpen = 'Datas/Temp/Visuel.png'
            img.save(self.PathFilejpgToOpen)
            self.AffichVisuel(self.PathFilejpgToOpen)
            self.AjoutVisuelBoite()

    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 FrmLift(self, _):
        self.MainAppli.FrmLift()

    def CacheFrmAjout(self, _):
        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 = 2
        self.MainAppli.MAJInfo()
        self.MainAppli.parent.focus_force()
        self.MainAppli.FrmLift()
        self.MainAppli.ModifEnCours = False
