from AppliDef import *
from FrmZoom import *
from EtagProduits import ModifListDanger


class FrmInfosTP(tk.Toplevel):
    def __init__(self, container, TP, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.TP = TP

        self.TabProd = None
        self.TabMat = None
        self.TabSol = None
        self.BtnSolSuiv = None
        self.BtnSolvantSuiv = None
        self.ListProd = []
        self.ListMat = []
        self.ListSol = []
        self.TabZoom = None
        self.ZoomActif = False
        self.TypeTab = 0
        self.MelangeSol = False
        self.MelangeSolvant = False
        self.ListMats = []
        self.ListMelSolvant = []
        self.ListSols = []
        self.ListMelSol = []

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmInfo/Fond/Fond.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/FrmInfo/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.753)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.11)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        if self.MainAppli.BaseEnCours == 'CHIMIE':
            self.CanvasMenu = CanvasInWindow('Media/FrmInfo/FondMenu/', self.RatioX, self.RatioY,
                                             self.CanvasFrmFond, tk.CENTER, int(self.SX * 0.5), int(self.SY * 0.48), 0)
            self.MenuOnglets = MenuOnglets(self.CanvasFrmFond, int(self.SX * 0.5), int(self.SY * 0.985), RatioX, RatioY,
                                           0, 'Matériel', 'Produits', 'Solutions', self.MainAppli.SizeFont,
                                           self.ActionAffichMat, self.ActionAffichProduits, self.ActionAffichSolutions)
        elif self.MainAppli.BaseEnCours == 'PHYS':
            self.CanvasMenu = CanvasInWindow('Media/FrmInfo/FondMenu/', self.RatioX, self.RatioY,
                                             self.CanvasFrmFond, tk.CENTER, int(self.SX * 0.5), int(self.SY * 0.52), 0)

        self.CanvasMenu.CanvasListIma.bind('<Motion>', self.MoveOnCanvas)

        self.ActionAffichMat()

        self.CanvasFrmFond.focus_set()
        self.CanvasFrmFond.pack()

    def ActionAffichMat(self):
        if self.TP:
            self.AffichMat()

    def ActionAffichProduits(self):
        if self.TP:
            self.AffichProduits()
        else:
            self.MenuOnglets.MenuSelected[1] = False
            self.MenuOnglets.ListCanvasMenu[1].itemconfig(self.MenuOnglets.ListImgMenu[1],
                                                          image=self.MenuOnglets.ListMenu[1][1])
            self.MenuOnglets.ListCanvasMenu[0].itemconfig(self.MenuOnglets.ListImgMenu[0],
                                                          image=self.MenuOnglets.ListMenu[0][2])
            self.MenuOnglets.MenuSelected[0] = True

    def ActionAffichSolutions(self):
        if self.TP:
            self.AffichSolutions()
        else:
            self.MenuOnglets.MenuSelected[2] = False
            self.MenuOnglets.ListCanvasMenu[2].itemconfig(self.MenuOnglets.ListImgMenu[2],
                                                          image=self.MenuOnglets.ListMenu[2][1])
            self.MenuOnglets.ListCanvasMenu[0].itemconfig(self.MenuOnglets.ListImgMenu[0],
                                                          image=self.MenuOnglets.ListMenu[0][2])
            self.MenuOnglets.MenuSelected[0] = True

    def AffichMat(self):
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("SELECT " + "MATERIEL, QUANTITE, LIEU" +
                                       " FROM TP WHERE TITRE = \"" + self.TP[0] + "\" order by MATERIEL")
            self.ListMats = self.MainAppli.cur.fetchall()
        elif self.MainAppli.BaseEnCours == 'PHYS':
            self.MainAppli.curphys.execute("SELECT " + "MATERIEL, QUANTITE, LIEU" +
                                           " FROM TP WHERE TITRE = \"" + self.TP[0] + "\" order by MATERIEL")
            self.ListMats = self.MainAppli.curphys.fetchall()

        self.ListMat = []
        for i in range(len(self.ListMats)):
            if self.ListMats[i][0] != '' and self.ListMats[i][0] is not None:
                self.ListMat.append(self.ListMats[i])

        self.EffaceMenu()
        self.TabMat = Tableau(self.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.TypeTab = 0
        self.TabMat.scrollable_canvas.canvas.bind('<Double-1>', self.ZoomTab)
        for r in range(self.TabMat.NLine):
            for i in range(self.TabMat.NCol):
                self.TabMat.TabLabels[r][i].bind('<Double-1>', self.ZoomTab)

        nl = 0
        for i in range(len(self.ListMat)):
            if self.ListMat[i][0] != '' and self.ListMat[i][0] is not None:
                for j in range(3):
                    self.TabMat.TabLabels[nl][j]['text'] = self.ListMat[i][j]
                nl = nl + 1

        self.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD', text="Informations - Matériel du TP")

    def AffichProduits(self):
        self.MainAppli.cur.execute("SELECT " + "PRODUIT, QUANTITE, UNITMES" +
                                   " FROM TP WHERE TITRE = \"" + self.TP[0] + "\" order by PRODUIT")
        ListProds = self.MainAppli.cur.fetchall()

        self.ListProd = []
        for i in range(len(ListProds)):
            if ListProds[i][0] != '' and ListProds[i][0] is not None:
                self.ListProd.append(ListProds[i])

        self.EffaceMenu()
        self.TabProd = Tableau(self.CanvasMenu, len(self.ListProd), 3, ['Désignation', 'Quantité/Gr', 'Unit. Mes.'],
                               [0.078, 0.02, 0.02],
                               AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                               AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0))

        self.TypeTab = 1
        self.TabProd.scrollable_canvas.canvas.bind('<Double-1>', self.ZoomTab)
        for r in range(self.TabProd.NLine):
            for i in range(self.TabProd.NCol):
                self.TabProd.TabLabels[r][i].bind('<Double-1>', self.ZoomTab)

        nl = 0
        for i in range(len(self.ListProd)):
            if self.ListProd[i][0] != '' and self.ListProd[i][0] is not None:
                for j in range(3):
                    self.TabProd.TabLabels[nl][j]['text'] = self.ListProd[i][j]
                nl = nl + 1
        if self.MainAppli.BaseEnCours == 'CHIMIE':
            self.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                       text="Informations - Produits chimiques du TP")
        elif self.MainAppli.BaseEnCours == 'PHYS':
            self.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                       text="Informations - Matériel du TP")
            for widget in self.CanvasMenu.CanvasListIma.winfo_children():
                widget.destroy()

    def AffichSolutions(self):
        self.MainAppli.cur.execute("SELECT " + "SOLUTE, SOLVANT, CONCENTRATION, QUANTITE, SOLUTE2, CONCENTRATION2, "
                                               "SOLVANT2" +
                                   " FROM TP WHERE TITRE = \"" + self.TP[0] + "\" order by SOLUTE")
        self.ListSol = self.MainAppli.cur.fetchall()

        self.ListSols = []
        for i in range(len(self.ListSol)):
            if self.ListSol[i][0] != '' and self.ListSol[i][0] is not None and self.ListSol[i][1] != '' \
                    and self.ListSol[i][1] is not None:
                self.ListSols.append(self.ListSol[i])

        self.EffaceMenu()
        self.TabSol = Tableau(self.CanvasMenu, len(self.ListSols), 4, ['Soluté', 'Solvant', 'C (mol/L)', 'Q/Gr (mL)'],
                              [0.058, 0.02, 0.02, 0.018], AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                              AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0))

        self.TypeTab = 2
        self.TabSol.scrollable_canvas.canvas.bind('<Double-1>', self.ZoomTab)
        for r in range(self.TabSol.NLine):
            for i in range(self.TabSol.NCol):
                self.TabSol.TabLabels[r][i].bind('<Double-1>', self.ZoomTab)

        nl = 0
        self.MelangeSol = False
        self.MelangeSolvant = False
        for i in range(len(self.ListSol)):
            if self.ListSol[i][4] != '' and self.ListSol[i][4] is not None:
                self.MelangeSol = True
            if self.ListSol[i][6] != '' and self.ListSol[i][6] is not None:
                self.MelangeSolvant = True
            if self.ListSol[i][0] != '' and self.ListSol[i][0] is not None \
                    and (self.ListSol[i][4] == '' or self.ListSol[i][4] is None):
                for j in range(4):
                    self.TabSol.TabLabels[nl][j]['text'] = self.ListSol[i][j]
                nl = nl + 1
        self.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD', text="Informations - Solutions du TP")

        if self.MelangeSol or self.MelangeSolvant:
            ChangeCursor(self.MainAppli.CanvasBtnSuiv)
            self.MainAppli.CanvasBtnSuiv.itemconfig(self.MainAppli.ImgCanvasBtnSuiv, image=self.MainAppli.ImgBtnSuiv[0])
            if self.MelangeSol:
                self.MainAppli.CanvasBtnSuiv.bind('<ButtonRelease-1>', self.AffichMelSol)
            elif self.MelangeSolvant:
                self.MainAppli.CanvasBtnSuiv.bind('<ButtonRelease-1>', self.AffichMelSolvant)
        else:
            ChangeCursor2(self.MainAppli.CanvasBtnSuiv)
        self.MainAppli.CanvasBtnRetour2.itemconfig(self.MainAppli.ImgCanvasBtnRetour2,
                                                   image=self.MainAppli.ImgBtnRetour2[2])
        ChangeCursor2(self.MainAppli.CanvasBtnRetour2)
        self.MainAppli.CanvasBtnRetour2.bind('<ButtonRelease-1>', self.Pass)

    def AffichMelSol(self, _):
        self.ActionAffichMelSol()

    def ActionAffichMelSol(self):
        self.EffaceMenu()
        self.ListMelSol = []
        for i in range(len(self.ListSol)):
            if self.ListSol[i][0] != '' and self.ListSol[i][0] is not None and self.ListSol[i][4] != '' \
                    and self.ListSol[i][4] is not None:
                self.ListMelSol.append(self.ListSol[i])
        self.TabSol = Tableau(self.CanvasMenu, len(self.ListMelSol), 5,
                              ['Soluté 1', 'C1 (mol/L)', 'Soluté 2', 'C2 (mol/L)', 'Q/Gr (mL)'],
                              [0.03, 0.02, 0.03, 0.02, 0.018],
                              AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                              AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0))
        self.TypeTab = 3
        self.TabSol.scrollable_canvas.canvas.bind('<Double-1>', self.ZoomTab)
        for r in range(self.TabSol.NLine):
            for i in range(self.TabSol.NCol):
                self.TabSol.TabLabels[r][i].bind('<Double-1>', self.ZoomTab)
        nl = 0
        for i in range(len(self.ListSol)):
            if self.ListSol[i][4] != '' and self.ListSol[i][4] is not None:
                self.TabSol.TabLabels[nl][0]['text'] = self.ListSol[i][0]
                self.TabSol.TabLabels[nl][1]['text'] = self.ListSol[i][2]
                self.TabSol.TabLabels[nl][2]['text'] = self.ListSol[i][4]
                self.TabSol.TabLabels[nl][3]['text'] = self.ListSol[i][5]
                self.TabSol.TabLabels[nl][4]['text'] = self.ListSol[i][3]
                nl = nl + 1

        if not self.MelangeSolvant:
            self.MainAppli.CanvasBtnSuiv.itemconfig(self.MainAppli.ImgCanvasBtnSuiv, image=self.MainAppli.ImgBtnSuiv[1])
            self.MainAppli.CanvasBtnSuiv.bind('<ButtonRelease-1>', self.AffichSol)
        else:
            self.MainAppli.CanvasBtnSuiv.itemconfig(self.MainAppli.ImgCanvasBtnSuiv, image=self.MainAppli.ImgBtnSuiv[0])
            self.MainAppli.CanvasBtnSuiv.bind('<ButtonRelease-1>', self.AffichMelSolvant)
            self.MainAppli.CanvasBtnRetour2.itemconfig(self.MainAppli.ImgCanvasBtnRetour2,
                                                       image=self.MainAppli.ImgBtnRetour2[1])
            ChangeCursor(self.MainAppli.CanvasBtnRetour2)
            self.MainAppli.CanvasBtnRetour2.bind('<ButtonRelease-1>', self.AffichSol)
        self.MainAppli.FrmLift()

        self.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD', text="Informations - Mélange de solutions du TP")

    def AffichMelSolvant(self, _):
        self.ActionAffichMelSolvant()

    def ActionAffichMelSolvant(self):
        self.EffaceMenu()
        self.ListMelSolvant = []
        for i in range(len(self.ListSol)):
            if self.ListSol[i][1] != '' and self.ListSol[i][1] is not None and self.ListSol[i][6] != '' \
                    and self.ListSol[i][6] is not None:
                self.ListMelSolvant.append(self.ListSol[i])
        self.TabSol = Tableau(self.CanvasMenu, len(self.ListMelSolvant), 5,
                              ['Solvant 1', 'C1 (%)', 'Solvant 2', 'C2 (%)', 'Q/Gr (mL)'],
                              [0.03, 0.019, 0.03, 0.019, 0.018],
                              AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                              AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0))
        self.TypeTab = 4
        self.TabSol.scrollable_canvas.canvas.bind('<Double-1>', self.ZoomTab)
        for r in range(self.TabSol.NLine):
            for i in range(self.TabSol.NCol):
                self.TabSol.TabLabels[r][i].bind('<Double-1>', self.ZoomTab)
        nl = 0
        for i in range(len(self.ListSol)):
            if self.ListSol[i][6] != '' and self.ListSol[i][6] is not None:
                self.TabSol.TabLabels[nl][0]['text'] = self.ListSol[i][1]
                self.TabSol.TabLabels[nl][1]['text'] = self.ListSol[i][2]
                self.TabSol.TabLabels[nl][2]['text'] = self.ListSol[i][6]
                self.TabSol.TabLabels[nl][3]['text'] = self.ListSol[i][5]
                self.TabSol.TabLabels[nl][4]['text'] = self.ListSol[i][3]
                nl = nl + 1

        self.MainAppli.CanvasBtnRetour2.itemconfig(self.MainAppli.ImgCanvasBtnRetour2,
                                                   image=self.MainAppli.ImgBtnRetour2[2])
        ChangeCursor2(self.MainAppli.CanvasBtnRetour2)
        self.MainAppli.CanvasBtnRetour2.bind('<ButtonRelease-1>', self.Pass)
        if not self.MelangeSol:
            self.MainAppli.CanvasBtnSuiv.itemconfig(self.MainAppli.ImgCanvasBtnSuiv, image=self.MainAppli.ImgBtnSuiv[1])
            self.MainAppli.CanvasBtnSuiv.bind('<ButtonRelease-1>', self.AffichSol)
        else:
            self.MainAppli.CanvasBtnSuiv.itemconfig(self.MainAppli.ImgCanvasBtnSuiv, image=self.MainAppli.ImgBtnSuiv[1])
            self.MainAppli.CanvasBtnSuiv.bind('<ButtonRelease-1>', self.AffichMelSol)
        self.MainAppli.FrmLift()

        self.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD', text="Informations - Mélange de solvants du TP")

    def AffichSol(self, _):
        self.AffichSolutions()
        self.lift()
        if self.TabZoom is not None and self.ZoomActif:
            self.TabZoom.lift()

    def MoveOnCanvas(self, _):
        if self.MainAppli.BaseEnCours == "CHIMIE":
            for i in range(3):
                if not self.MenuOnglets.MenuSelected[i]:
                    self.MenuOnglets.ListCanvasMenu[i].itemconfig(self.MenuOnglets.ListImgMenu[i],
                                                                  image=self.MenuOnglets.ListMenu[i][0])

    def EffaceMenu(self):
        for widget in self.CanvasMenu.CanvasListIma.winfo_children():
            widget.destroy()
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.CanvasBtnSuiv.itemconfig(self.MainAppli.ImgCanvasBtnSuiv, image=self.MainAppli.ImgBtnSuiv[2])
            if not self.MenuOnglets.MenuSelected[2]:
                ChangeCursor2(self.MainAppli.CanvasBtnSuiv)
            self.MainAppli.CanvasBtnSuiv.bind('<ButtonRelease-1>', self.Pass)

    def Pass(self, _):
        self.MainAppli.FrmLift()

    def ZoomTab(self, _):
        self.EffaceMenu()
        if self.ZoomActif:
            for widget in self.TabZoom.CanvasFrmFond.winfo_children():
                widget.destroy()
            self.TabZoom.AffichBtnQuit()
            if self.TypeTab == 0:
                self.TabZoom.AffichTabMat()
            elif self.TypeTab == 1:
                self.TabZoom.AffichTabProd()
            elif self.TypeTab == 2:
                self.TabZoom.AffichTabSol()
            elif self.TypeTab == 3:
                self.TabZoom.AffichTabMelSol()
            elif self.TypeTab == 4:
                self.TabZoom.AffichTabMelSolvant()
        else:
            self.TabZoom = FrmZoomTab(self.MainAppli.FrmTP.CanvasFrmFond, self.MainAppli.FrmTP.RatioX,
                                      self.MainAppli.FrmTP.RatioY, self.TypeTab, self)
            self.TabZoom.CanvasFrmFond.bind('<Button-1>', self.ClicOnCanvas)
            self.ZoomActif = True

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


class Tableau:
    def __init__(self, container, NLine, NCol, ListLabelCol, LabelWidth, Font1, Font2):
        self.NLine = NLine
        self.NCol = NCol
        self.FrameTableur = tk.Frame(container.CanvasListIma)
        container.CanvasListIma.create_window(int(container.wsize * 0.5),
                                              int(container.hsize * 0.5), anchor=tk.CENTER,
                                              window=self.FrameTableur)
        self.scrollable_canvas = ScrollableCanvas(self.FrameTableur, int(container.wsize * 0.965),
                                                  int(container.hsize * 0.945))
        self.scrollable_canvas.grid(row=1, column=1)

        self.TabLabelNCol = []
        self.TabLabels = []

        for r in range(NLine):
            self.TabLabelCol = []
            for i in range(NCol):
                self.TabLabelNCol.append(
                    tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                             width=int(container.wsize * LabelWidth[i]), height=2, bg='white', font=Font1))
                self.TabLabelNCol[i].grid(row=0, column=i)
                self.TabLabelCol.append(tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                                 width=int(container.wsize * LabelWidth[i]), bg='white', font=Font2))
                self.TabLabelCol[i].grid(row=r + 1, column=i)
                self.TabLabelNCol[i]['text'] = ListLabelCol[i]

            self.TabLabels.append(self.TabLabelCol)

        for r in range(NLine):
            for i in range(NCol):
                def GestEvt(evt, j=r):
                    return self.SelectLine(evt, j)

                self.TabLabels[r][i].bind('<Button-1>', GestEvt)
                ChangeCursor(self.TabLabels[r][i])

    def SelectLine(self, _, j):
        self.ActionUnSelect()
        for i in range(self.NCol):
            self.TabLabels[j][i].config(bg='#E0E0E0')

    def ActionUnSelect(self):
        for r in range(self.NLine):
            for i in range(self.NCol):
                self.TabLabels[r][i].config(bg='white')
