from AppliDef import *
from FrmInfoProdMat import Tableau, InfoMatChim, InfoMatPhys, DescriptMat
import re


class FrmPrepaMat(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.TabMat = False
        self.InfoMat = None
        self.ListMat = []
        self.DescriptMat = None

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

        coefY = float(ConfigResolution(self.MainAppli.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.CacheFrmAjout)

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

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond,
                                      self.TP[2] + ' - ' + self.TP[0] + ' - Préparation du matériel', '#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.331),
                                      int(self.SY * 0.965), int(self.SX * 0.003), int(self.SY * 0.031), tk.NW)
        self.AffichMat()
        self.CanvasMenu2 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.965), int(self.SX * 0.5), int(self.SY * 0.031), tk.N)

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

        if len(self.ListMat) > 0:
            self.AffichStock(0)

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

        self.CanvasFrmFond.pack()

    def AffichMat(self):
        LabelInCanvas(self.CanvasMenu1.CanvasMenu, 'Matériel du TP', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.004), tk.NW)
        self.ListMat = []
        for i in range(len(self.MainAppli.InfoTP.ListMat)):
            if self.MainAppli.InfoTP.ListMat[i][0] != '' and self.MainAppli.InfoTP.ListMat[i][0] is not None:
                self.ListMat.append(self.MainAppli.InfoTP.ListMat[i])

        self.TabMat = Tableau(self.CanvasMenu1.CanvasMenu, len(self.ListMat), 3,
                              ['Désignation', 'Quantité', 'Lieu'],
                              [0.078, 0.02, 0.02],
                              AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                              AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)

        nl = 0
        for i in range(len(self.ListMat)):
            for j in range(3):
                self.TabMat.TabLabels[nl][j]['text'] = self.ListMat[i][j]
                if nl == 0:
                    self.TabMat.TabLabels[nl][j].config(bg='#E0E0E0')
            nl = nl + 1

    def AffichStock(self, IndexElt):
        self.EffaceMenus()
        LabelInCanvas(self.CanvasMenu2.CanvasMenu, 'Stock / Fournisseur du matériel sélectionné', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.004), tk.NW)
        LabelInCanvas(self.CanvasMenu3.CanvasMenu, 'Descriptif du matériel sélectionné', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.004), tk.NW)
        ListMats = []
        if self.MainAppli.BaseEnCours == "CHIMIE":
            try:
                self.MainAppli.cur.execute("SELECT " + self.MainAppli.ListChampsTabMat +
                                           " FROM MATERIEL WHERE " + 'NOMS = "' +
                                           self.ListMat[IndexElt][0] + '" order by NOMS')
                ListMats = self.MainAppli.cur.fetchall()
            except:
                self.MainAppli.cur.execute("SELECT " + self.MainAppli.ListChampsTabMat +
                                           " FROM MATERIEL WHERE " + 'NOMS LIKE \"%' +
                                           self.ListMat[IndexElt][0].replace('"', "") + '%\" order by NOMS')
                ListMats = self.MainAppli.cur.fetchall()
            finally:
                if len(ListMats) == 0:
                    Mat = re.split(' ', self.ListMat[IndexElt][0].replace('"', ""))
                    c = 1
                    while len(ListMats) == 0:
                        NomMat = Mat[0]
                        for i in range(1, len(Mat) - c):
                            NomMat = NomMat + ' ' + Mat[i]
                        self.MainAppli.cur.execute("SELECT " + self.MainAppli.ListChampsTabMat +
                                                   " FROM MATERIEL WHERE " + 'NOMS LIKE \"%' +
                                                   NomMat + '%\" order by NOMS')
                        ListMats = self.MainAppli.cur.fetchall()
                        c += 1
                        if c == len(Mat):
                            break
        elif self.MainAppli.BaseEnCours == "PHYS":
            try:
                self.MainAppli.curphys.execute("SELECT " + self.MainAppli.ListChampsTabMatPhys +
                                               " FROM MATERIEL WHERE " + 'NOMS = "' +
                                               self.ListMat[IndexElt][0] + '" order by NOMS')
                ListMats = self.MainAppli.curphys.fetchall()
            except:
                self.MainAppli.curphys.execute("SELECT " + self.MainAppli.ListChampsTabMatPhys +
                                               " FROM MATERIEL WHERE " + 'NOMS LIKE \"%' +
                                               self.ListMat[IndexElt][0].replace('"', "") + '%\" order by NOMS')
                ListMats = self.MainAppli.curphys.fetchall()

            finally:
                if len(ListMats) == 0:
                    Mat = re.split(' ', self.ListMat[IndexElt][0].replace('"', ""))
                    c = 1
                    while len(ListMats) == 0:
                        NomMat = Mat[0]
                        for i in range(1, len(Mat) - c):
                            NomMat = NomMat + ' ' + Mat[i]
                        self.MainAppli.curphys.execute("SELECT " + self.MainAppli.ListChampsTabMatPhys +
                                                       " FROM MATERIEL WHERE " + 'NOMS LIKE \"%' +
                                                       NomMat + '%\" order by NOMS')
                        ListMats = self.MainAppli.curphys.fetchall()
                        c += 1
                        if c == len(Mat):
                            break

        if len(ListMats) > 0:
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.InfoMat = InfoMatChim(self.CanvasMenu2.CanvasMenu, ListMats[0],
                                           self.MainAppli.cur, self.MainAppli.SizeFont, self.RatioX,
                                           self.RatioY, 1, self.MainAppli.LieuxStockMatChim)

                self.DescriptMat = DescriptMat(self.CanvasMenu3.CanvasMenu, ListMats[0], "CHIMIE",
                                               self.MainAppli.SizeFont, self.RatioX, self.RatioY)
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.InfoMat = InfoMatPhys(self.CanvasMenu2.CanvasMenu, ListMats[0],
                                           self.MainAppli.curphys, self.MainAppli.SizeFont, self.RatioX, self.RatioY,
                                           1, self.MainAppli.LieuxStockMatPhys)

                self.DescriptMat = DescriptMat(self.CanvasMenu3.CanvasMenu, ListMats[0], "PHYS",
                                               self.MainAppli.SizeFont, self.RatioX, self.RatioY)

    def EffaceMenus(self):
        for widget in self.CanvasMenu2.CanvasMenu.winfo_children():
            widget.destroy()
        for widget in self.CanvasMenu3.CanvasMenu.winfo_children():
            widget.destroy()
        if self.InfoMat is not None:
            self.CanvasMenu2.CanvasMenu.delete(self.InfoMat.NomMat)
            self.CanvasMenu2.CanvasMenu.delete(self.InfoMat.TitreStock)
            self.CanvasMenu2.CanvasMenu.delete(self.InfoMat.TitreFournisseur)
            self.InfoMat = None

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

    def CacheFrmAjout(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.ListBtnActionV[5].CanvasBtn.itemconfig(self.MainAppli.ListBtnActionV[5].ImgCanvasBtn,
                                                                  image=self.MainAppli.ListBtnActionV[5].ImgBtn[0])
        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.ListBtnActionV[5].CanvasBtn.itemconfig(self.MainAppli.ListBtnActionV[5].ImgCanvasBtn,
                                                                  image=self.MainAppli.ListBtnActionV[5].ImgBtn[4])
        self.destroy()
        if self.MainAppli.OldNAction != 0:
            self.MainAppli.NAction = self.MainAppli.OldNAction
        else:
            self.MainAppli.NAction = 3
        self.MainAppli.MAJInfo()
        self.MainAppli.parent.lift()
        self.MainAppli.FrmLift()
        self.MainAppli.ModifEnCours = False
