from FrmDef import *
import os
from PIL import Image, ImageTk, ImageGrab
import ctypes
import sys
import fitz
import shutil
import winsound
from win32 import win32api
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.units import cm
from reportlab.lib.pagesizes import A4
from datetime import datetime
import webview
import time
import threading
import webbrowser


def ModifString(ch):
    chars = "\\/'`*_{}[]()>#+-.:!$, "
    for c in chars:
        ch = ch.replace(c, '')
    return ch


def DeterminAspectRatio():
    screen = ctypes.windll.user32
    AspectRatio = screen.GetSystemMetrics(0) / screen.GetSystemMetrics(1)
    if AspectRatio == 16 / 9:
        if screen.GetSystemMetrics(0) == 1920:
            Nconfig = 0
        else:
            Nconfig = 1
    elif AspectRatio == 683 / 384:
        Nconfig = 2
    else:
        Nconfig = 3
    return Nconfig


def ConfigResolution(NConfig, Type, cur):
    Resol = ['ConfigUn', 'ConfigDeux', 'ConfigTrois', 'defaut']
    cur.execute("select " + Resol[NConfig] + " From Resol WHERE Type = '" + Type + "'")
    Val = cur.fetchall()
    return Val[0][0]


def RedimImg(wsize, hsize, chemin):
    ListDossierImage = os.listdir(chemin)
    ListImages = []
    for elt in ListDossierImage:
        ListImages.append(Image.open(chemin + elt))
    ListImgRedim = []
    for img in ListImages:
        img = img.resize((wsize, hsize), Image.ANTIALIAS)
        ListImgRedim.append(ImageTk.PhotoImage(img))
    return ListImgRedim


def ChargeDossierImg(chemin, wpercent, wpercent2):
    ListDossierImage = os.listdir(chemin)
    ListImages = []
    for elt in ListDossierImage:
        ListImages.append(Image.open(chemin + elt))
    ListImgRedim = []
    wsize = 0
    hsize = 0
    for img in ListImages:
        wsize = int((float(img.size[0]) * float(wpercent)))
        hsize = int((float(img.size[1]) * float(wpercent2)))
        img = img.resize((wsize, hsize), Image.ANTIALIAS)
        ListImgRedim.append(ImageTk.PhotoImage(img))
    return ListImgRedim, wsize, hsize


def CanInWindow(chemin, ratio, ratio2, conteneur, align, XW, YW, n):
    ListIma, wsize, hsize = ChargeDossierImg(chemin, ratio, ratio2)
    CanvasListIma = CanvasApp(conteneur, width=wsize, height=hsize)
    conteneur.create_window(XW, YW, anchor=align, window=CanvasListIma)
    ImgCanvasListIma = CanvasListIma.create_image(0, 0, anchor=tk.NW, image=ListIma[n])
    return ListIma, wsize, hsize, CanvasListIma, ImgCanvasListIma


def ChangeCursor(Can):
    Can.bind('<Enter>', lambda action: Can.configure(cursor='hand2'))
    Can.bind('<Leave>', lambda action: Can.configure(cursor=''))


def ChangeCursor2(Can):
    Can.bind('<Enter>', lambda action: Can.configure(cursor=''))
    Can.bind('<Leave>', lambda action: Can.configure(cursor=''))


def CalculNEtag(NElt, Max):
    if NElt <= Max:
        NEtag = 0
    elif NElt % Max != 0:
        NEtag = NElt // Max
    else:
        NEtag = (NElt // Max) - 1
    return NEtag


def Imprim(Can, Path, Name):
    x = Can.winfo_rootx()
    y = Can.winfo_rooty()
    w = Can.winfo_width()
    h = Can.winfo_height()
    image = ImageGrab.grab((x, y, x + w, y + h))
    image.save(Path + Name)

    im = Image.open(Path + Name)
    pdf_filename = Path + Name + ".pdf"
    im.save(pdf_filename, "PDF", resolution=100.0, save_all=True)
    return pdf_filename


def SaveToPDF(Can, Path, Name):
    x = Can.winfo_rootx()
    y = Can.winfo_rooty()
    w = Can.winfo_width()
    h = Can.winfo_height()
    image = ImageGrab.grab((x, y, x + w, y + h))
    image.save(Path + Name)

    im = Image.open(Path + Name)
    pdf_filename = Path + str(datetime.now()).replace(':', '') + ".pdf"
    im.save(pdf_filename, "PDF", resolution=100.0, save_all=True)
    return pdf_filename


def FormatDate(Date):
    LDate = Date.split('-')
    date = str("%02d" % int(LDate[2].split(' ')[0]))
    for i in range(1, -1, -1):
        date = date + '-' + str("%02d" % int(LDate[i]))
    return date


class BtnAction:
    def __init__(self, container, X, Y, RX, RY, path):
        self.ImgBtn, self.wsize, self.hsize, self.CanvasBtn, self.ImgCanvasBtn = CanInWindow(path, RX, RY, container,
                                                                                             tk.CENTER, X, Y, 0)
        ChangeCursor(self.CanvasBtn)
        self.CanvasBtn.bind('<ButtonPress-1>',
                            lambda action: self.CanvasBtn.itemconfig(self.ImgCanvasBtn, image=self.ImgBtn[1]))


class ScrollableCanvas(tk.Frame):
    def __init__(self, parent, W, H, *args, **kw):
        tk.Frame.__init__(self, parent, *args, **kw)

        self.canvas = tk.Canvas(self, bg='#FFFFFF', width=W, height=H, scrollregion=(0, 0, W, H))

        vbar = tk.Scrollbar(self, orient=tk.VERTICAL)
        vbar.pack(side=tk.RIGHT, fill=tk.Y)
        vbar.config(command=self.canvas.yview)

        hbar = tk.Scrollbar(self, orient=tk.HORIZONTAL)
        hbar.pack(side=tk.BOTTOM, fill=tk.X)
        hbar.config(command=self.canvas.xview)

        self.canvas.config(yscrollcommand=vbar.set)
        self.canvas.config(xscrollcommand=hbar.set)
        self.canvas.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)

        self.interior = tk.Frame(self.canvas)
        self.canvas.create_window(0, 0, window=self.interior, anchor=tk.NW)

        def _configure_interior(_):
            size = (self.interior.winfo_reqwidth(), self.interior.winfo_reqheight())
            self.canvas.config(scrollregion="0 0 %s %s" % size)

        self.interior.bind('<Configure>', _configure_interior)


class CanvasInWindow:
    def __init__(self, chemin, ratio, ratio2, conteneur, align, XW, YW, n):
        self.ListIma, self.wsize, self.hsize, self.CanvasListIma, self.ImgCanvasListIma = CanInWindow(chemin, ratio,
                                                                                                      ratio2, conteneur,
                                                                                                      align, XW, YW, n)


class ImgInCanvas:
    def __init__(self, container, Path, ratio, align, X, Y):
        img = Image.open(Path)
        imgwsize = int(int(container['width']) * ratio)
        imghsize = int(imgwsize * float(img.size[1]) / float(img.size[0]))
        if imghsize > int(int(container['height']) * ratio):
            imghsize = int(int(container['height']) * ratio)
            imgwsize = int(imghsize * float(img.size[0]) / float(img.size[1]))
        img = img.resize((imgwsize, imghsize), Image.ANTIALIAS)
        self.Img = ImageTk.PhotoImage(img)
        self.CanvasImg = CanvasApp(container, width=img.size[0], height=img.size[1])
        container.create_window(X, Y, anchor=align, window=self.CanvasImg)
        self.ImgCanvasImg = self.CanvasImg.create_image(0, 0, anchor=tk.NW, image=self.Img)


class CanvasMenu:
    def __init__(self, container, Path, W, H, X, Y, align):
        self.ImgMenu = []
        self.ImgMenu = RedimImg(W, H, Path)
        self.CanvasMenu = CanvasApp(container, width=W, height=H)
        container.create_window(X, Y, anchor=align, window=self.CanvasMenu)
        self.ImgCanvasMenu = self.CanvasMenu.create_image(0, 0, anchor=tk.NW, image=self.ImgMenu[0])


class EntryData:
    def __init__(self, container, W, X, Y, align, Font):
        self.Data = tk.StringVar()
        self.EntryData = tk.Entry(container, width=W, font=Font, textvariable=self.Data)
        container.create_window(X, Y, anchor=align, window=self.EntryData)


class FrmPDF:
    def __init__(self, container, file, ratio, SY, X, Y, W, H):
        self.PDF, Wsize, Hsize = ChargePDF(file, ratio)
        self.NbrPagesPDF = len(self.PDF)
        self.FilePDFAOuvrir = file
        self.Container = container
        self.W = W

        self.FrameDoc = tk.Frame(container, bg='#F7F7F7')
        container.create_window(X, Y, anchor=tk.CENTER, window=self.FrameDoc)
        self.CanvasDoc = CanvasApp(self.FrameDoc, width=W, height=H, scrollregion=(0, 0, Wsize, Hsize))
        vbar = tk.Scrollbar(self.FrameDoc, orient=tk.VERTICAL)
        vbar.pack(side=tk.RIGHT, fill=tk.Y)
        vbar.config(command=self.CanvasDoc.yview)

        hbar = tk.Scrollbar(self.FrameDoc, orient=tk.HORIZONTAL)
        hbar.pack(side=tk.BOTTOM, fill=tk.X)
        hbar.config(command=self.CanvasDoc.xview)

        self.CanvasDoc.config(yscrollcommand=vbar.set, xscrollcommand=hbar.set)
        self.CanvasDoc.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)
        ChangeCursor(self.CanvasDoc)

        self.PageAffich = 0
        self.ImgCanvasDoc = self.CanvasDoc.create_image(int(W / 2), 0, anchor=tk.N, image=self.PDF[self.PageAffich])

        self.CanvasScale = CanvasApp(container, width=int(W * 1.035), height=int(SY * 0.048), bg='#F7F7F7')
        container.create_window(X, int(Y + H / 2 + SY * 0.01), anchor=tk.N, window=self.CanvasScale)
        self.DefilPage = tk.Scale(self.CanvasScale, orient=tk.HORIZONTAL, length=W * 1.03, showvalue=0)
        self.CanvasScale.create_window(0, 0, anchor=tk.NW, window=self.DefilPage)

        self.DefilPage.config(from_=0, to=self.NbrPagesPDF - 1, resolution=1)
        self.DefilPage.config(command=self.NavigPDF)
        self.DefilPage.bind('<MouseWheel>', self.MouseWheelDefil)
        self.CanvasDoc.bind('<MouseWheel>', self.MouseWheelDefil)

        self.LegendeNPage = self.CanvasScale.create_text(int(W * 0.515), int(SY * 0.025),
                                                         text='Page ' + str(self.PageAffich + 1) + '/' +
                                                              str(self.NbrPagesPDF), anchor=tk.N,
                                                         font=AppliFont('Helvetica', 10, 'normal', 0))
        self.CanvasScale.addtag_withtag('LegendeNPage', self.LegendeNPage)

    def NavigPDF(self, _):
        self.PageAffich = self.DefilPage.get()
        self.AffichPagePDF(self.PageAffich)
        self.CanvasScale.itemconfigure('LegendeNPage',
                                       text='Page ' + str(self.PageAffich + 1) + '/' + str(self.NbrPagesPDF))

    def MouseWheelDefil(self, event):
        if event.delta == -120:
            self.PageAffich = self.PageAffich - 1
            if self.PageAffich < 0:
                self.PageAffich = 0
        if event.delta == 120:
            self.PageAffich = self.PageAffich + 1
            if self.PageAffich > self.NbrPagesPDF - 1:
                self.PageAffich = self.NbrPagesPDF - 1
        self.DefilPage.set(self.PageAffich)

    def AffichPagePDF(self, page):
        self.CanvasDoc.delete(self.ImgCanvasDoc)
        self.ImgCanvasDoc = self.CanvasDoc.create_image(int(self.W / 2), 0, anchor=tk.N, image=self.PDF[page])


class NoPDF:
    def __init__(self, container, file, X, Y, RX, RY):
        self.ImgNoPdf = []
        img = Image.open(file)
        imgwsize = int((float(img.size[0]) * float(RX)))
        imghsize = int((float(img.size[1]) * float(RY)))
        img = img.resize((imgwsize, imghsize), Image.ANTIALIAS)
        self.ImgNoPdf.append(ImageTk.PhotoImage(img))

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


class PagePDF:
    def __init__(self, container, file, W, X, Y, npage):
        self.PDF, Wsize, Hsize = ChargePDF2(file, W)
        self.NbrPagesPDF = len(self.PDF)
        self.FilePDFAOuvrir = file
        self.Container = container

        self.PageAffich = npage
        self.ImgCanvasDoc = self.Container.create_image(X, Y, anchor=tk.CENTER, image=self.PDF[self.PageAffich])


def ChargePDF(chemin, ratio):
    FilePDF = fitz.open(chemin)
    ListImgPDF = []
    Wsize = 0
    Hsize = 0
    for i in range(FilePDF.pageCount):
        page = FilePDF.loadPage(i)
        pix = page.getPixmap()
        mode = "RGBA" if pix.alpha else "RGB"
        img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
        Wsize = int(pix.width * ratio)
        Hsize = int(pix.height * ratio)
        img = img.resize((Wsize, Hsize), Image.ANTIALIAS)
        ListImgPDF.append(ImageTk.PhotoImage(img))

    return ListImgPDF, Wsize, Hsize


def ChargePDF2(chemin, W):
    FilePDF = fitz.open(chemin)
    ListImgPDF = []
    Wsize = 0
    Hsize = 0
    for i in range(FilePDF.pageCount):
        page = FilePDF.loadPage(i)
        pix = page.getPixmap()
        mode = "RGBA" if pix.alpha else "RGB"
        ratio = 1
        img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
        Wsize = int(pix.width * ratio)
        while Wsize > W:
            ratio = ratio - 0.001
            Wsize = int(pix.width * ratio)
        Hsize = int(pix.height * ratio)
        img = img.resize((Wsize, Hsize), Image.ANTIALIAS)
        ListImgPDF.append(ImageTk.PhotoImage(img))

    return ListImgPDF, Wsize, Hsize


def CreateCadre(container, x0, y0, x1, y1):
    Line1 = container.create_line(x0, y0, x1, y0)
    container.addtag_withtag('Line1', Line1)
    Line2 = container.create_line(x0, y0, x0, y1)
    container.addtag_withtag('Line2', Line2)
    Line3 = container.create_line(x1, y0, x1, y1)
    container.addtag_withtag('Line3', Line3)
    Line4 = container.create_line(x0, y1, x1, y1)
    container.addtag_withtag('Line4', Line4)


def CalculDefilMax(l, Max):
    if len(l) <= Max:
        defilmax = 0
    elif len(l) % Max != 0:
        defilmax = len(l) // Max
    else:
        defilmax = (len(l) // Max) - 1
    return defilmax


class MenuOnglets:
    def __init__(self, container, X, Y, RX, RY, N, text1, text2, text3, SizeFont, Action1, Action2, Action3):
        self.MenuSelected = [False, False, False]
        self.MenuSelected[N] = True

        self.ImgMenu, self.Menuwsize, self.Menuhsize, self.CanvasMenu, self.ImgCanvasMenu = CanInWindow(
            'Media/FrmInfo/BarreMenu/Fond/', RX, RY, container, tk.CENTER, X, Y, 0)

        self.ListCanvasMenu = []
        self.ListImgMenu = []
        self.ListMenu = []
        self.Action1 = Action1
        self.Action2 = Action2
        self.Action3 = Action3

        self.MenuPara, wsize, hsize, self.CanvasMenuPara, self.ImgMenuPara = CanInWindow(
            'Media/FrmInfo/BarreMenu/Onglets/', RX, RY, self.CanvasMenu, tk.CENTER,
            int(self.Menuwsize * 0.168), int(self.Menuhsize * 0.5), 0)
        self.ListCanvasMenu.append(self.CanvasMenuPara)
        self.ListImgMenu.append(self.ImgMenuPara)
        self.ListMenu.append(self.MenuPara)
        self.CanvasMenuPara.create_text(int(wsize * 0.5), int(hsize * 0.5), text=text1,
                                        font=AppliFont('Helvetica', SizeFont, 'normal', 0), anchor=tk.CENTER)

        self.MenuModel, wsize, hsize, self.CanvasMenuModel, self.ImgMenuModel = CanInWindow(
            'Media/FrmInfo/BarreMenu/Onglets/', RX, RY, self.CanvasMenu, tk.CENTER,
            int(self.Menuwsize * 0.5), int(self.Menuhsize * 0.5), 0)
        self.ListCanvasMenu.append(self.CanvasMenuModel)
        self.ListImgMenu.append(self.ImgMenuModel)
        self.ListMenu.append(self.MenuModel)
        self.CanvasMenuModel.create_text(int(wsize * 0.5), int(hsize * 0.5), text=text2,
                                         font=AppliFont('Helvetica', SizeFont, 'normal', 0), anchor=tk.CENTER)

        self.MenuTab, wsize, hsize, self.CanvasMenuTab, self.ImgMenuTab = CanInWindow(
            'Media/FrmInfo/BarreMenu/Onglets/', RX, RY, self.CanvasMenu, tk.CENTER,
            int(self.Menuwsize * 0.835), int(self.Menuhsize * 0.5), 0)
        self.ListCanvasMenu.append(self.CanvasMenuTab)
        self.ListImgMenu.append(self.ImgMenuTab)
        self.ListMenu.append(self.MenuTab)
        self.CanvasMenuTab.create_text(int(wsize * 0.5), int(hsize * 0.5), text=text3,
                                       font=AppliFont('Helvetica', SizeFont, 'normal', 0), anchor=tk.CENTER)

        for i in range(3):
            def GestEvt(evt, j=i):
                return self.MoveOnMenu(evt, j)

            def GestEvt2(evt, j=i):
                return self.ClicOnMenu(evt, j)

            self.ListCanvasMenu[i].bind('<Motion>', GestEvt)
            self.ListCanvasMenu[i].bind('<Button-1>', GestEvt2)
            ChangeCursor(self.ListCanvasMenu[i])

        self.ListCanvasMenu[N].itemconfig(self.ListImgMenu[N], image=self.ListMenu[N][2])

    def MoveOnMenu(self, _, j):
        self.InitOnglets()
        if not self.MenuSelected[j]:
            self.ListCanvasMenu[j].itemconfig(self.ListImgMenu[j], image=self.ListMenu[j][1])

    def ClicOnMenu(self, _, j):
        self.InitOnglets2()
        if not self.MenuSelected[j]:
            self.ListCanvasMenu[j].itemconfig(self.ListImgMenu[j], image=self.ListMenu[j][2])
            self.MenuSelected[j] = True
        if j == 0:
            self.Action1()
        elif j == 1:
            self.Action2()
        elif j == 2:
            self.Action3()

    def InitOnglets(self):
        for i in range(3):
            if not self.MenuSelected[i]:
                self.ListCanvasMenu[i].itemconfig(self.ListImgMenu[i], image=self.ListMenu[i][0])

    def InitOnglets2(self):
        for i in range(3):
            ChangeCursor(self.ListCanvasMenu[i])
            self.MenuSelected[i] = False
            self.ListCanvasMenu[i].itemconfig(self.ListImgMenu[i], image=self.ListMenu[i][0])


class TableauMain:
    def __init__(self, container, NLine, NCol, ListLabelCol, LabelWidth, Font1, Font2):
        self.NLine = NLine
        self.NCol = NCol
        self.container = container
        self.LabelWidth = LabelWidth
        self.Font2 = Font2
        self.FrameTableur = tk.Frame(container)
        container.create_window(int(int(container['width']) * 0.5),
                                int(int(container['height']) * 0.513), anchor=tk.CENTER,
                                window=self.FrameTableur)
        self.scrollable_canvas = ScrollableCanvas(self.FrameTableur, int(int(container['width']) * 0.965),
                                                  int(int(container['height']) * 0.945))
        self.scrollable_canvas.grid(row=1, column=1)

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

        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(int(container['width']) * 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(int(container['width']) * 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)
            self.LineSelected.append(False)

        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()
        if not self.LineSelected[j]:
            self.InitLineSelected()
            for i in range(self.NCol):
                self.TabLabels[j][i].config(bg='#E0E0E0')
            self.LineSelected[j] = True
        else:
            self.InitLineSelected()
            for i in range(self.NCol):
                self.TabLabels[j][i].config(bg='white')

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

    def InitLineSelected(self):
        for r in range(self.NLine):
            self.LineSelected[r] = False

    def AjoutLine(self):
        self.TabLabelCol = []
        for i in range(self.NCol):
            self.TabLabelCol.append(tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                             width=int(int(self.container['width']) * self.LabelWidth[i]), bg='white',
                                             font=self.Font2))
            self.TabLabelCol[i].grid(row=self.NLine + 1, column=i)

        self.TabLabels.append(self.TabLabelCol)
        self.LineSelected.append(False)

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

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

        self.NLine = self.NLine + 1


class Tableau:
    def __init__(self, container, NLine, NCol, ListLabelCol, LabelWidth, Font1, Font2, MainAppli):
        self.MainAppli = MainAppli
        self.NLine = NLine
        self.NCol = NCol
        self.FrameTableur = tk.Frame(container)
        container.create_window(int(int(container['width']) * 0.5),
                                int(int(container['height']) * 0.513), anchor=tk.CENTER,
                                window=self.FrameTableur)
        self.scrollable_canvas = ScrollableCanvas(self.FrameTableur, int(int(container['width']) * 0.965),
                                                  int(int(container['height']) * 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(int(container['width']) * 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(int(container['width']) * 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('<ButtonRelease-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')


class MiniTableau:
    def __init__(self, container, NLine, NCol, ListLabelCol, LabelWidth, Font1, Font2, MainAppli):
        self.MainAppli = MainAppli
        self.NLine = NLine
        self.NCol = NCol
        self.FrameTableur = tk.Frame(container)
        container.create_window(int(int(container['width']) * 0.5),
                                int(int(container['height']) * 0.5), anchor=tk.CENTER,
                                window=self.FrameTableur)
        self.scrollable_canvas = ScrollableCanvas(self.FrameTableur, int(int(container['width']) * 0.95),
                                                  int(int(container['height']) * 0.92))
        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.GROOVE,
                             width=int(int(container['width']) * 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.GROOVE,
                                                 width=int(int(container['width']) * 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('<ButtonRelease-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')


class Scrollable_ListBox:
    def __init__(self, container, X, Y, W, H):
        self.CanvasListBox = CanvasApp(container, bg='white')
        container.create_window(X, Y, anchor=tk.NW, window=self.CanvasListBox)
        self.ScrollbarListBoxV = tk.Scrollbar(self.CanvasListBox)
        self.ScrollbarListBoxV.pack(side=tk.RIGHT, fill=tk.Y)
        self.ListBox = tk.Listbox(self.CanvasListBox, width=W, height=H, activestyle='none')
        self.ListBox.config(yscrollcommand=self.ScrollbarListBoxV.set)
        self.ScrollbarListBoxV.config(command=self.ListBox.yview)

        self.ScrollbarListBoxH = tk.Scrollbar(self.CanvasListBox, orient=tk.HORIZONTAL)
        self.ScrollbarListBoxH.pack(side=tk.BOTTOM, fill=tk.X)
        self.ListBox.config(xscrollcommand=self.ScrollbarListBoxH.set)
        self.ScrollbarListBoxH.config(command=self.ListBox.xview)

        self.ListBox.pack()


class AffichTabMultiPage:
    def __init__(self, container, List, LineMax, Titre, SizeFont, NCol, Entete, LCol, Appli):
        self.MainAppli = Appli
        self.Titre = Titre
        self.SizeFont = SizeFont
        self.Container = container
        self.List = List
        self.LineMax = LineMax
        self.CountPageMat = 1
        self.ImgBtnSuivMat = None
        self.CanvasBtnSuivMat = None
        self.ImgCanvasBtnSuivMat = None
        self.CountLineMat = 0
        self.ImgBtnPrecMat = None
        self.CanvasBtnPrecMat = None
        self.ImgCanvasBtnPrecMat = None
        self.NCol = NCol
        self.Entete = Entete
        self.LCol = LCol

        if len(List) > LineMax:
            self.CountLineMat = LineMax
            self.ImgBtnSuivMat, wsize, hsize, self.CanvasBtnSuivMat, self.ImgCanvasBtnSuivMat = CanInWindow(
                'Media/FrmMain/BtnSuiv/', self.MainAppli.RatioX, self.MainAppli.RatioY, container, tk.CENTER,
                int(int(container['width']) * 0.995), int(int(container['height']) * 0.015), 0)
            ChangeCursor(self.CanvasBtnSuivMat)
            self.CanvasBtnSuivMat.bind('<ButtonRelease-1>', self.InfoSuiv)
        else:
            self.CountLineMat = len(self.List)
        LabelInCanvas(container, Titre, '#E0E0E0',
                      AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                      int(int(container['width']) * 0.01), int(int(container['height']) * 0.004), tk.NW)
        self.LabelNpage = LabelInCanvas(container, 'Page ' + str(self.CountPageMat), '#E0E0E0',
                                        AppliFont('Helvetica', self.SizeFont, 'normal', 0),
                                        int(int(container['width']) * 0.98), int(int(container['height']) * 0.004),
                                        tk.NE)
        self.TabMat = Tableau(self.Container, self.CountLineMat, NCol, Entete, LCol,
                              AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                              AppliFont('Helvetica', self.SizeFont, 'normal', 0), self)
        for i in range(self.CountLineMat):
            for j in range(NCol):
                self.TabMat.TabLabels[i][j]['text'] = self.List[i][j]

    def InfoSuiv(self, _):
        self.EffaceMenu()
        self.CountPageMat = self.CountPageMat + 1
        LabelInCanvas(self.Container, self.Titre, '#E0E0E0',
                      AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                      int(int(self.Container['width']) * 0.01), int(int(self.Container['height']) * 0.004), tk.NW)
        self.LabelNpage = LabelInCanvas(self.Container, 'Page ' + str(self.CountPageMat), '#E0E0E0',
                                        AppliFont('Helvetica', self.SizeFont, 'normal', 0),
                                        int(int(self.Container['width']) * 0.98),
                                        int(int(self.Container['height']) * 0.004), tk.NE)
        self.TabMat = Tableau(self.Container, self.LineMax, self.NCol, self.Entete, self.LCol,
                              AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                              AppliFont('Helvetica', self.SizeFont, 'normal', 0), self)
        nl = 0
        if self.CountPageMat * self.LineMax < len(self.List):
            CountFin = self.CountPageMat * self.LineMax
            self.ImgBtnSuivMat, wsize, hsize, self.CanvasBtnSuivMat, self.ImgCanvasBtnSuivMat = CanInWindow(
                'Media/FrmMain/BtnSuiv/', self.MainAppli.RatioX, self.MainAppli.RatioY, self.Container, tk.CENTER,
                int(int(self.Container['width']) * 0.995),
                int(int(self.Container['height']) * 0.015), 0)
            ChangeCursor(self.CanvasBtnSuivMat)
            self.CanvasBtnSuivMat.bind('<ButtonRelease-1>', self.InfoSuiv)
            self.ImgBtnPrecMat, wsize, hsize, self.CanvasBtnPrecMat, self.ImgCanvasBtnPrecMat = CanInWindow(
                'Media/FrmMain/BtnSuiv/', self.MainAppli.RatioX, self.MainAppli.RatioY, self.Container, tk.CENTER,
                int(int(self.Container['width']) * 0.985),
                int(int(self.Container['height']) * 0.015), 1)
            ChangeCursor(self.CanvasBtnPrecMat)
            self.CanvasBtnPrecMat.bind('<ButtonRelease-1>', self.InfoPrec)
        else:
            CountFin = len(self.List)
            self.ImgBtnSuivMat, wsize, hsize, self.CanvasBtnSuivMat, self.ImgCanvasBtnSuivMat = CanInWindow(
                'Media/FrmMain/BtnSuiv/', self.MainAppli.RatioX, self.MainAppli.RatioY, self.Container, tk.CENTER,
                int(int(self.Container['width']) * 0.995),
                int(int(self.Container['height']) * 0.015), 1)
            ChangeCursor(self.CanvasBtnSuivMat)
            self.CanvasBtnSuivMat.bind('<ButtonRelease-1>', self.InfoPrec)
        for i in range(self.CountLineMat, CountFin):
            for j in range(self.NCol):
                self.TabMat.TabLabels[nl][j]['text'] = self.List[i][j]
            nl = nl + 1
        self.CountLineMat = self.CountPageMat * self.LineMax
        self.MainAppli.ActivModifTab()

    def InfoPrec(self, _):
        self.EffaceMenu()
        LabelInCanvas(self.Container, self.Titre, '#E0E0E0',
                      AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                      int(int(self.Container['width']) * 0.01), int(int(self.Container['height']) * 0.004), tk.NW)
        self.TabMat = Tableau(self.Container, self.LineMax, self.NCol, self.Entete, self.LCol,
                              AppliFont('Helvetica', self.SizeFont, 'bold', 0),
                              AppliFont('Helvetica', self.SizeFont, 'normal', 0), self)
        nl = 0
        self.CountPageMat = self.CountPageMat - 1
        self.LabelNpage = LabelInCanvas(self.Container, 'Page ' + str(self.CountPageMat), '#E0E0E0',
                                        AppliFont('Helvetica', self.SizeFont, 'normal', 0),
                                        int(int(self.Container['width']) * 0.98),
                                        int(int(self.Container['height']) * 0.004), tk.NE)
        if self.CountPageMat > 1:
            CountDeb = (self.CountPageMat - 1) * self.LineMax
            self.ImgBtnSuivMat, wsize, hsize, self.CanvasBtnSuivMat, self.ImgCanvasBtnSuivMat = CanInWindow(
                'Media/FrmMain/BtnSuiv/', self.MainAppli.RatioX, self.MainAppli.RatioY, self.Container, tk.CENTER,
                int(int(self.Container['width']) * 0.995), int(int(self.Container['height']) * 0.015), 0)
            ChangeCursor(self.CanvasBtnSuivMat)
            self.CanvasBtnSuivMat.bind('<ButtonRelease-1>', self.InfoSuiv)
            self.ImgBtnPrecMat, wsize, hsize, self.CanvasBtnPrecMat, self.ImgCanvasBtnPrecMat = CanInWindow(
                'Media/FrmMain/BtnSuiv/', self.MainAppli.RatioX, self.MainAppli.RatioY, self.Container, tk.CENTER,
                int(int(self.Container['width']) * 0.985), int(int(self.Container['height']) * 0.015), 1)
            ChangeCursor(self.CanvasBtnPrecMat)
            self.CanvasBtnPrecMat.bind('<ButtonRelease-1>', self.InfoPrec)
        else:
            CountDeb = 0
            self.ImgBtnSuivMat, wsize, hsize, self.CanvasBtnSuivMat, self.ImgCanvasBtnSuivMat = CanInWindow(
                'Media/FrmMain/BtnSuiv/', self.MainAppli.RatioX, self.MainAppli.RatioY, self.Container, tk.CENTER,
                int(int(self.Container['width']) * 0.995), int(int(self.Container['height']) * 0.015), 0)
            ChangeCursor(self.CanvasBtnSuivMat)
            self.CanvasBtnSuivMat.bind('<ButtonRelease-1>', self.InfoSuiv)

        for i in range(CountDeb, self.CountPageMat * self.LineMax):
            for j in range(self.NCol):
                self.TabMat.TabLabels[nl][j]['text'] = self.List[i][j]
            nl = nl + 1
        self.CountLineMat = self.CountPageMat * self.LineMax
        self.MainAppli.ActivModifTab()

    def EffaceMenu(self):
        for widget in self.Container.winfo_children():
            widget.destroy()
        if self.MainAppli.TriPar:
            self.MainAppli.AffichSelectListClass(self.MainAppli.LClass)


class CreatePDF:
    def __init__(self, Img, Pos, Quant, XY, W, H, Path, Name):
        File = Path + Name
        Can = Canvas("{0}".format(File), pagesize=A4)
        ComptFin = Pos - 1 + Quant
        for i in range(Pos - 1, ComptFin):
            Can.drawImage(Img, XY[i][0] * cm, XY[i][1] * cm, width=W * cm, height=H * cm, mask="auto")
        Can.save()
        # win32api.ShellExecute(0, "print", Name, None, Path, 0)


class BtnPlusMoins:
    def __init__(self, Container, RatioX, RatioY, Titre, Max, Min, SizeFont, X, Y, Appli):
        self.MainAppli = Appli
        self.Max = Max
        self.Min = Min
        self.Titre = Container.create_text(int(int(Container['width']) * X), int(int(Container['height']) * Y),
                                           text=Titre, font=AppliFont('Helvetica', SizeFont + 1, 'bold', 1),
                                           anchor=tk.W)

        self.Val = LabelInCanvas(Container, Min, 'white', AppliFont('Helvetica', SizeFont + 2, 'bold', 0),
                                 int(int(Container['width']) * (X + 0.04)), int(int(Container['height']) * (Y + 0.03)),
                                 tk.NW)
        self.Val.Label.config(width=int(int(Container['width']) * 0.006),
                              height=int(int(Container['height']) * 0.003), relief=tk.RIDGE)

        self.BtnPlus = BtnAction(Container, int(int(Container['width']) * (X + 0.12)),
                                 int(int(Container['height']) * (Y + 0.042)), RatioX * 1.1, RatioY * 1.1,
                                 'Media/FrmEtiq/BtnPlus/')
        self.BtnPlus.CanvasBtn.bind('<ButtonRelease-1>', self.ValPlus)
        self.BtnMoins = BtnAction(Container, int(int(Container['width']) * (X + 0.12)),
                                  int(int(Container['height']) * (Y + 0.062)), RatioX * 1.1,
                                  RatioY * 1.1, 'Media/FrmEtiq/BtnMoins/')
        self.BtnMoins.CanvasBtn.bind('<ButtonRelease-1>', self.ValMoins)

    def ValPlus(self, _):
        self.BtnPlus.CanvasBtn.itemconfig(self.BtnPlus.ImgCanvasBtn, image=self.BtnPlus.ImgBtn[0])
        if int(self.Val.Label['text']) < self.Max:
            self.Val.Label.config(text=str(int(self.Val.Label['text']) + 1))
        self.MainAppli.CallbackPlusMoins()

    def ValMoins(self, _):
        self.BtnMoins.CanvasBtn.itemconfig(self.BtnMoins.ImgCanvasBtn, image=self.BtnMoins.ImgBtn[0])
        if int(self.Val.Label['text']) > self.Min:
            self.Val.Label.config(text=str(int(self.Val.Label['text']) - 1))
        self.MainAppli.CallbackPlusMoins()


class ChercheWeb:
    def __init__(self, Titre, Nom, Appli):
        self.MainAppli = Appli
        self.screen = None
        window = webview.create_window(Titre, 'https://www.google.fr/search?q=' + Nom,
                                       confirm_close=True)
        webview.start(self.resize, window)
        window.events.closed += self.on_closed()
        window.events.closing += self.on_closing()

    def resize(self, window):
        self.screen = ctypes.windll.user32
        window.move(-10, -5)
        window.resize(int(self.screen.GetSystemMetrics(0) * 1.05), int(self.screen.GetSystemMetrics(1) * 1.05))

    def on_closing(self):
        t = threading.Thread(target=self.MainAppli.CloseWeb)
        t.start()

    def on_closed(self):
        self.MainAppli.CloseWeb()


class AffichPDF:
    def __init__(self, Titre, Nom, Appli):
        self.MainAppli = Appli
        self.screen = None
        window = webview.create_window(Titre, Nom, confirm_close=True)
        webview.start(self.resize, window)
        window.events.closed += self.on_closed()
        window.events.closing += self.on_closing()

    def resize(self, window):
        self.screen = ctypes.windll.user32
        window.move(-10, -5)
        window.resize(int(self.screen.GetSystemMetrics(0) * 1.05), int(self.screen.GetSystemMetrics(1) * 1.05))

    def on_closing(self):
        t = threading.Thread(target=self.MainAppli.ClosePDF)
        t.start()

    def on_closed(self):
        self.MainAppli.ClosePDF()
