from AppliDef import *


class FrmEtagMat(tk.Toplevel):
    def __init__(self, container, ListMat, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.ListMat = ListMat
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.ListMatEtag = []
        self.NEtag = 0
        self.NMatEtag = 0

        if self.MainAppli.BaseEnCours == 'CHIMIE':
            self.TypeMat = 0
        elif self.MainAppli.BaseEnCours == 'PHYS':
            self.TypeMat = 1

        self.ImgEtagMat, wsize, hsize, self.CanvasEtagMat, self.ImgCanvasEtagMat = CanInWindow(
            'Media/FrmEtagMat/Fond/', self.RatioX, self.RatioY, container, tk.CENTER,
            int(self.MainAppli.SX * 0.462), int(self.MainAppli.SY * 0.527), 0)
        self.DefilMat = tk.Scale(self.CanvasEtagMat, orient=tk.HORIZONTAL, length=wsize, showvalue=0)
        self.CanvasEtagMat.create_window(int(wsize / 2), int(hsize * 0.99), anchor=tk.CENTER, window=self.DefilMat)
        self.DefilMat.config(command=self.DefilEtagMat)
        self.defilmax = CalculDefilMax(self.ListMat, 12)
        self.DefilMat.config(from_=0, to=self.defilmax, resolution=1)
        self.DefilMat.bind('<MouseWheel>', self.MouseWheelDefil)

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

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmEtagMat/Etag/')
        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.176)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.083)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()
        self.AffichMat(self.NEtag)
        if len(ListMat) > 0:
            self.SelectMat(0)
        self.CanvasFrmFond.bind('<MouseWheel>', self.MouseWheelSelect)
        self.CanvasFrmFond.bind('<Button-1>', self.ClicOnCanvas)
        self.CanvasFrmFond.focus_set()
        self.CanvasFrmFond.pack()

    def DefilEtagMat(self, _):
        if self.MainAppli.NAction != 5:
            for widget in self.CanvasFrmFond.winfo_children():
                widget.destroy()
            for i in range(len(self.ListMatEtag)):
                if self.ListMatEtag[i].NomMat is not None:
                    self.CanvasFrmFond.delete(self.ListMatEtag[i].NomMat)
                if self.ListMatEtag[i].NomMat1 is not None:
                    self.CanvasFrmFond.delete(self.ListMatEtag[i].NomMat1)
                if self.ListMatEtag[i].NomMat2 is not None:
                    self.CanvasFrmFond.delete(self.ListMatEtag[i].NomMat2)
            self.NEtag = self.DefilMat.get()
            self.MainAppli.NEtag = self.NEtag
            self.ListMatEtag = []
            self.AffichMat(self.NEtag)
            if 0 < self.MainAppli.IndexElt - self.NEtag * 12 < 12:
                self.SelectMat(self.MainAppli.IndexElt - self.NEtag * 12)
            else:
                self.SelectMat(0)
        else:
            self.DefilMat.set(self.NEtag)
            self.MainAppli.FrmLift()

    def MouseWheelDefil(self, event):
        if event.delta == -120:
            self.NEtag = self.NEtag - 1
            if self.NEtag < 0:
                self.NEtag = 0
        if event.delta == 120:
            self.NEtag = self.NEtag + 1
            if self.NEtag > self.defilmax:
                self.NEtag = self.defilmax
        self.DefilMat.set(self.NEtag)
        self.MainAppli.NEtag = self.NEtag

    def MouseWheelSelect(self, event):
        if event.delta == -120:
            self.NMatEtag = self.NMatEtag - 1
            if self.NMatEtag < 0:
                if self.NEtag > 0:
                    self.NEtag = self.NEtag - 1
                    self.NMatEtag = 11
                    self.MainAppli.IndexElt = self.NMatEtag + self.NEtag * 12
                    self.MainAppli.NEtag = self.NEtag
                    self.DefilMat.set(self.NEtag)
                else:
                    self.NMatEtag = 0
                    self.SelectMat(self.NMatEtag)
            else:
                self.SelectMat(self.NMatEtag)
        if event.delta == 120:
            self.NMatEtag = self.NMatEtag + 1
            if self.NMatEtag > 11 or self.NMatEtag + self.NEtag * 12 > len(self.ListMat) - 1:
                if self.NEtag < self.defilmax:
                    self.NEtag = self.NEtag + 1
                    self.NMatEtag = 0
                    self.MainAppli.IndexElt = self.NMatEtag + self.NEtag * 12
                    self.MainAppli.NEtag = self.NEtag
                    self.DefilMat.set(self.NEtag)
                else:
                    self.NMatEtag = self.NMatEtag - 1
                    self.SelectMat(self.NMatEtag)
            else:
                self.SelectMat(self.NMatEtag)

    def AffichMat(self, NEtag):
        NMat = 0
        for l in range(3):
            if NMat >= len(self.ListMat):
                break
            for k in range(4):
                NMat = k + l * 4 + NEtag * 12
                if NMat >= len(self.ListMat):
                    break
                Visuel = ''
                if self.ListMat[NMat][1] is not None:
                    Visuel = self.ListMat[NMat][1]
                self.ListMatEtag.append(Boite(self.CanvasFrmFond, self.ListMat[NMat][0], Visuel,
                                              int(self.SX * 0.125 + k * self.SX * 0.25),
                                              int(self.SY * 0.21 + l * self.SY * 0.323),
                                              self.RatioX * 1.2, self.RatioX * 1.2, self.TypeMat))

        for i in range(len(self.ListMatEtag)):
            ChangeCursor(self.ListMatEtag[i].CanvasImg)

            def GestEvt(_, j=i):
                return self.SelectMat(j)

            self.ListMatEtag[i].CanvasImg.bind('<ButtonRelease-1>', GestEvt)
            try:
                self.ListMatEtag[i].CanvasImgEtiqMat.bind('<ButtonRelease-1>', GestEvt)
            except:
                pass

    def SelectMat(self, j):
        if self.MainAppli.NAction != 202 and self.MainAppli.NAction != 2021 and self.MainAppli.NAction != 5:
            for i in range(len(self.ListMatEtag)):
                if self.ListMatEtag[i].NomMat is not None:
                    self.CanvasFrmFond.itemconfigure(self.ListMatEtag[i].NomMat, fill='black')
                if self.ListMatEtag[i].NomMat1 is not None:
                    self.CanvasFrmFond.itemconfigure(self.ListMatEtag[i].NomMat1, fill='black')
                if self.ListMatEtag[i].NomMat2 is not None:
                    self.CanvasFrmFond.itemconfigure(self.ListMatEtag[i].NomMat2, fill='black')
            if self.ListMatEtag[j].NomMat is not None:
                self.CanvasFrmFond.itemconfigure(self.ListMatEtag[j].NomMat, fill='blue')
            if self.ListMatEtag[j].NomMat1 is not None:
                self.CanvasFrmFond.itemconfigure(self.ListMatEtag[j].NomMat1, fill='blue')
            if self.ListMatEtag[j].NomMat2 is not None:
                self.CanvasFrmFond.itemconfigure(self.ListMatEtag[j].NomMat2, fill='blue')

            self.MainAppli.ListBoxProduits.selection_clear(0, tk.END)
            self.MainAppli.IndexElt = j + self.NEtag * 12
            self.NMatEtag = j
            self.MainAppli.ListBoxProduits.selection_set(self.MainAppli.IndexElt)
            self.MainAppli.ListBoxProduits.see(self.MainAppli.IndexElt)

            if not self.MainAppli.Init:
                self.MainAppli.InfoMat.Mat = self.ListMat[self.MainAppli.IndexElt]
                if self.MainAppli.InfoMat.MenuOnglets.MenuSelected[0]:
                    self.MainAppli.InfoMat.AffichStock()
                elif self.MainAppli.InfoMat.MenuOnglets.MenuSelected[1]:
                    self.MainAppli.InfoMat.AffichDescript()
                elif self.MainAppli.InfoMat.MenuOnglets.MenuSelected[2]:
                    self.MainAppli.InfoMat.AffichNotice()
                self.MainAppli.InfoMat.lift()
            self.lift()
        elif self.MainAppli.NAction == 5:
            self.MainAppli.FrmLift()

    def ClicOnCanvas(self, _):
        if self.MainAppli.NAction == 5:
            self.MainAppli.FrmLift()


class Boite:
    def __init__(self, container, Nom, Visuel, X, Y, RX, RY, TypeMat):
        self.ImgBoite = []
        img = Image.open('Media/FrmEtagMat/Boite/Boite.bmp')
        imgwsize = int((float(img.size[0]) * float(RX * 0.75)))
        imghsize = int((float(img.size[1]) * float(RY * 0.8)))
        img = img.resize((imgwsize, imghsize), Image.ANTIALIAS)
        self.ImgBoite.append(ImageTk.PhotoImage(img))

        self.CanvasImg = CanvasApp(container, width=imgwsize, height=imghsize)
        container.create_window(X, Y, anchor=tk.CENTER, window=self.CanvasImg)
        self.ImgCanvasImgBoite = self.CanvasImg.create_image(0, 0, anchor=tk.NW, image=self.ImgBoite[0])

        if len(Nom) >= 35:
            sizefont = 8
        else:
            sizefont = 10
        if len(Nom) >= 41:
            self.NomMat = None
            (Nom1, Nom2) = (Nom[:len(Nom) // 2], Nom[len(Nom) // 2:])
            self.NomMat1 = container.create_text(X, Y + imghsize * 0.63, text=Nom1 + '-',
                                                 font=AppliFont('Helvetica', sizefont, 'bold', 0), anchor=tk.CENTER)
            self.NomMat2 = container.create_text(X, Y + imghsize * 0.69, text=Nom2,
                                                 font=AppliFont('Helvetica', sizefont, 'bold', 0), anchor=tk.CENTER)
        else:
            self.NomMat1 = None
            self.NomMat2 = None
            self.NomMat = container.create_text(X, Y + imghsize * 0.66, text=Nom,
                                                font=AppliFont('Helvetica', sizefont, 'bold', 0), anchor=tk.CENTER)

        if Visuel != '':
            self.ImgEtiqMat = []
            if TypeMat == 0:
                img = Image.open('Datas/VisuelMatChim/' + Visuel)
            elif TypeMat == 1:
                img = Image.open('Datas/VisuelMatPhys/' + Visuel)
            imgEtiqwsize = int(imgwsize * 0.5)
            imgEtiqhsize = int(imgEtiqwsize * float(img.size[1]) / float(img.size[0]))
            if imgEtiqhsize > imghsize * 0.5:
                imgEtiqhsize = int(imghsize * 0.5)
                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.CanvasImg, width=imgEtiqwsize, height=imgEtiqhsize)
            self.CanvasImg.create_window(int(imgwsize * 0.5), int(imghsize * 0.63), anchor=tk.CENTER,
                                         window=self.CanvasImgEtiqMat)
            self.ImgCanvasImgEtiqMat = self.CanvasImgEtiqMat.create_image(0, 0, anchor=tk.NW,
                                                                          image=self.ImgEtiqMat[0])

            CreateCadre(self.CanvasImg, int(imgwsize * 0.495 - imgEtiqwsize / 2),
                        int(imghsize * 0.625 - imgEtiqhsize / 2),
                        int(imgwsize * 0.505 - imgEtiqwsize / 2) + imgEtiqwsize,
                        int(imghsize * 0.635 - imgEtiqhsize / 2) + imgEtiqhsize)

        else:
            if len(Nom) > 30:
                NomBoite = Nom.split(' ')
                for i in range(len(NomBoite)):
                    self.CanvasImg.create_text(int(imgwsize * 0.5), int(imghsize * 0.5 + i * imghsize * 0.05),
                                               text=NomBoite[i],
                                               font=AppliFont('Calibri', sizefont, 'bold', 0), anchor=tk.CENTER)
            else:
                self.CanvasImg.create_text(int(imgwsize * 0.5), int(imghsize * 0.5), text=Nom,
                                           font=AppliFont('Calibri', sizefont, 'bold', 0), anchor=tk.CENTER)
