from AppliDef import *


class FrmTabRecapProd(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.ListProd = []
        self.TabProd = None
        self.ClassListe = []
        self.StringClass = tk.StringVar()
        self.ListClass = None
        self.TypeTri = ''
        self.TriPar = False
        self.TitreClass = ''
        self.LClass = 0
        self.EntryManuelVal = None
        self.ListModif = []
        self.ImgBtnRetour, self.CanvasBtnRetour, self.ImgCanvasBtnRetour = None, None, None
        self.LCell = []
        self.MenuClicDroit = []
        self.NProdSelect = 0

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

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

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

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

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

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond, 'Tableau récapitulatif des produits chimiques en stock',
                                      '#E0E0E0', AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)

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

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

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

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

        self.AffichTabRecapProd()

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

        self.CanvasFrmFond.pack()

    def ActionAffichTabRecapProd(self, _):
        self.AffichTabRecapProd()

    def AffichTabRecapProd(self):
        self.EffaceMenu()
        if self.StringTri.get() == 'Ordre alphabétique':
            self.TriPar = False
            self.MainAppli.cur.execute("select " + "NOMS, SYNO, LIEUX, QSTOCK, QUTIL, UNITMES"
                                       + " from PRODUITS order by NOMS")
            self.ListProd = self.MainAppli.cur.fetchall()
            self.LCell = [0.034, 0.034, 0.014, 0.014, 0.014, 0.009]
            self.TabProd = AffichTabMultiPage(self.CanvasMenu.CanvasMenu, self.ListProd, 40,
                                              'Produits chimiques classés par ordre alphabétique',
                                              self.MainAppli.SizeFont, 6,
                                              ['Noms', 'Synonymes', 'Lieux de stockage', 'Quantité en stock',
                                               'Quantité utilisée / an', 'Unit. Mes.'], self.LCell, self)
            self.ActivModifTab()

        elif self.StringTri.get() == 'Lieux de stockage':
            self.TriPar = True
            self.TypeTri = "LIEUX"
            self.TitreClass = 'Produits chimiques classés par lieu de stockage:'
            self.LClass = 0.015
            self.AffichListClass(8)

        elif self.StringTri.get() == 'Fonctions':
            self.TriPar = True
            self.TypeTri = "FONCTION"
            self.TitreClass = 'Produits chimiques classés par fonction:'
            self.LClass = 0.015
            self.AffichListClass(7)

        elif self.StringTri.get() == 'Fournisseurs':
            self.TriPar = True
            self.TypeTri = "FOURNISSEUR"
            self.TitreClass = 'Produits chimiques classés par fournisseur:'
            self.LClass = 0.015
            self.AffichListClass(9)

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

    def AffichListClass(self, IndexClass):
        self.EffaceMenu()
        self.ClassListe = []
        for i in range(len(self.MainAppli.ListProduits)):
            if self.MainAppli.ListProduits[i][IndexClass] not in self.ClassListe:
                self.ClassListe.append(self.MainAppli.ListProduits[i][IndexClass])
        for i in range(len(self.ClassListe)):
            if self.ClassListe[i] == "":
                self.ClassListe[i] = "Sans"
        self.ClassListe.sort()
        if len(self.ClassListe) > 0:
            self.StringClass.set(self.ClassListe[0])

        self.TriProd()

    def ActionTriProd(self, _):
        self.EffaceMenu()
        self.TriProd()

    def TriProd(self):
        self.AffichSelectListClass(self.LClass)
        if self.StringClass.get() == "Sans":
            ChClass = ''
        else:
            ChClass = self.StringClass.get()
        self.MainAppli.cur.execute("SELECT " + "NOMS, SYNO, LIEUX, QSTOCK, QUTIL, UNITMES" +
                                   " FROM PRODUITS WHERE " + self.TypeTri + " = \"" + ChClass
                                   + "\" order by NOMS")
        self.ListProd = self.MainAppli.cur.fetchall()

        self.TabProd = AffichTabMultiPage(self.CanvasMenu.CanvasMenu, self.ListProd, 40,
                                          self.TitreClass, self.MainAppli.SizeFont, 6,
                                          ['Noms', 'Synonymes', 'Lieux de stockage', 'Quantité en stock',
                                           'Quantité utilisée / an', 'Unit. Mes.'],
                                          [0.034, 0.034, 0.014, 0.014, 0.014, 0.009], self)

        self.ActivModifTab()

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

    def Imprim(self, _):
        self.BtnPrint.CanvasBtn.itemconfig(self.BtnPrint.ImgCanvasBtn, image=self.BtnPrint.ImgBtn[0])
        FileToImprim = Imprim(self.CanvasMenu.CanvasMenu, 'Datas/Print/', 'tmp.bmp')
        AffichPDF('Tableau récapitulatif des produits chimiques en stock', FileToImprim, self)
        self.MainAppli.parent.lift()
        self.lift()
        self.CanvasFrmFond.focus_set()

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

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

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

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

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

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

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

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

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

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

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

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

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

    def ModifVal(self, _, i, j):
        if self.EntryManuelVal is None:
            self.EntryManuelVal = tk.Entry(self.TabProd.TabMat.scrollable_canvas.interior, text='',
                                           width=int(int(self.CanvasMenu.CanvasMenu['width']) * self.LCell[j]),
                                           font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                           justify='right')
            self.EntryManuelVal.grid(row=i + 1, column=j)
            self.EntryManuelVal.insert(0, self.TabProd.TabMat.TabLabels[i][j]['text'])
            self.EntryManuelVal.focus_set()

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

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

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

    def ValidModifVal(self, _, i, j):
        OldVal = self.TabProd.TabMat.TabLabels[i][j]['text']
        if self.EntryManuelVal.get() != '':
            self.TabProd.TabMat.TabLabels[i][j]['text'] = self.EntryManuelVal.get()

            if j == 3 or j == 4:
                try:
                    float(self.EntryManuelVal.get().replace(',', '.'))
                except:
                    self.EntryManuelVal.delete(0, tk.END)
                    self.EntryManuelVal.insert(0, OldVal)
                    self.TabProd.TabMat.TabLabels[i][j]['text'] = OldVal
            elif j == 5:
                if self.EntryManuelVal.get() != "g" and self.EntryManuelVal.get() != "mL" and \
                        self.EntryManuelVal.get().upper() != "UNIT":
                    self.EntryManuelVal.delete(0, tk.END)
                    self.EntryManuelVal.insert(0, OldVal)
                    self.TabProd.TabMat.TabLabels[i][j]['text'] = OldVal

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

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

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

    def SaveModifVal(self, i, j):
        REQUETE = ['SYNO', 'LIEUX', 'QSTOCK', 'QUTIL', 'UNITMES', 'PRIXHT']
        self.MainAppli.cur.execute("UPDATE PRODUITS SET '" + REQUETE[j - 1] + "' ='" +
                                   self.TabProd.TabMat.TabLabels[i][j]['text']
                                   + "' WHERE NOMS='" + self.TabProd.TabMat.TabLabels[i][0]['text'] + "'")
        self.MainAppli.DataBaseChimie.commit()
        self.MainAppli.SaveListModifDTB('Chimie', 'Mise à jour données Produit chimique - ' +
                                        self.TabProd.TabMat.TabLabels[i][0]['text'])

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

    def ActionAnnul(self, _):
        self.CanvasBtnRetour.itemconfig(self.ImgCanvasBtnRetour, image=self.ImgBtnRetour[1])
        self.TabProd.TabMat.TabLabels[self.ListModif[-1][0]][self.ListModif[-1][1]]['text'] = self.ListModif[-1][2]
        self.SaveModifVal(self.ListModif[-1][0], self.ListModif[-1][1])
        del self.ListModif[-1]
        if len(self.ListModif) == 0:
            self.CanvasBtnRetour.destroy()
            self.CanvasBtnRetour = None

    def VoirProd(self):
        self.MainAppli.IndexElt = self.MainAppli.ListNomProd.index(
            self.TabProd.TabMat.TabLabels[self.NProdSelect][0]['text'])
        self.ActionVoirProd()

    def ModifProd(self):
        self.MainAppli.IndexElt = self.MainAppli.ListNomProd.index(
            self.TabProd.TabMat.TabLabels[self.NProdSelect][0]['text'])
        self.ActionModifProd()

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

    def ActionModifProd(self):
        self.ActionVoirProd()
        self.MainAppli.ActionV(3)

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

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

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

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