from FrmDef import *
import os
from PIL import Image, ImageTk
import fitz
import ctypes
import threading


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, XW, YW, n):
    ListIma, wsize, hsize = ChargeDossierImg(chemin, ratio, ratio2)
    CanvasListIma = CanvasApp(conteneur, width=wsize, height=hsize)
    conteneur.create_window(XW, YW, anchor=tk.CENTER, window=CanvasListIma)
    ImgCanvasListIma = CanvasListIma.create_image(0, 0, anchor=tk.NW, image=ListIma[n])
    return ListIma, wsize, hsize, CanvasListIma, ImgCanvasListIma


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


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


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


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


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 DeterminAspectRatio():
    screen = ctypes.windll.user32
    AspectRatio = screen.GetSystemMetrics(0) / screen.GetSystemMetrics(1)
    if AspectRatio == 683 / 384:
        Nconfig = 0
    elif AspectRatio == 16 / 9:
        if screen.GetSystemMetrics(0) == 1920:
            Nconfig = 1
        else:
            Nconfig = 2
    elif AspectRatio == 8 / 5:
        Nconfig = 3
    else:
        Nconfig = 0
    return Nconfig


def ConfigResolution(Nconfig, cle):
    dictresolconfig = {}
    with open("resolconfig", 'r') as fichierconfig:
        for line in fichierconfig:
            listline = line.split(";")
            dictresolconfig[listline[0]] = listline[1].strip()
    listconfig = dictresolconfig.get(cle).split(',')
    return float(listconfig[Nconfig])


class MyThread(threading.Thread):
    def __init__(self, target):
        threading.Thread.__init__(self)
        self.target = target
        self.StopThread = False

    def run(self):
        while not self.StopThread:
            self.target()

    def stop(self):
        self.StopThread = True


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

        self.FrameDoc = tk.Frame(container, bg='white')
        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.CanvasDoc.bind('<Double-2>', self.OuvreAcrobat)

        self.PageAffich = 0
        self.ImgCanvasDoc = self.CanvasDoc.create_image(0, 0, anchor=tk.NW, image=self.PDF[self.PageAffich])

        self.PDFNavigM, wsize, hsize, self.CanvasPDFNavigM, self.ImgPDFNavigM = CanInWindow(
            'Media/CanvasDetails/Doc/Navig/', RX, RY, container,
            int(X - W * DX), int(Y + H * DY), 0)
        ChangeCursor(self.CanvasPDFNavigM)
        self.CanvasPDFNavigM.bind('<Button-1>', self.NavigPDFM)

        self.PDFNavigP, wsize, hsize, self.CanvasPDFNavigP, self.ImgPDFNavigP = CanInWindow(
            'Media/CanvasDetails/Doc/Navig/', RX, RY, container,
            int(X + W * DX), int(Y + H * DY), 1)
        ChangeCursor(self.CanvasPDFNavigP)
        self.CanvasPDFNavigP.bind('<Button-1>', self.NavigPDFP)

    def NavigPDFM(self, _):
        if self.PageAffich > 0:
            self.PageAffich = self.PageAffich - 1
            self.AffichPagePDF(self.PageAffich)

    def NavigPDFP(self, _):
        if self.PageAffich < self.NbrPagesPDF - 1:
            self.PageAffich = self.PageAffich + 1
            self.AffichPagePDF(self.PageAffich)

    def AffichPagePDF(self, page):
        self.ImgCanvasDoc = self.CanvasDoc.create_image(0, 0, anchor=tk.NW, image=self.PDF[page])

    def OuvreAcrobat(self, _):
        os.startfile(self.FilePDFAOuvrir.replace('/', '\\'))


class NoPDF:
    def __init__(self, container, X, Y, RX, RY):
        self.ImgNoPdf = []
        img = Image.open('Media/CanvasDetails/Logo/NoPdf.jpg')
        imgwsize = int((float(img.size[0]) * float(RX)))
        imghsize = int((float(img.size[1]) * float(RY)))
        img = img.resize((imgwsize, imghsize), Image.ANTIALIAS)
        img = img.transpose(Image.ROTATE_90)
        self.ImgNoPdf.append(ImageTk.PhotoImage(img))

        self.CanvasImgNoPdf = CanvasApp(container, width=imghsize, height=imgwsize)
        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 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,
                                                                                             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 DataEntry:
    def __init__(self, container, Text, Color, Font, X, Y, W, coef):
        self.LabelXmin = LabelInCanvas(container, Text, Color, Font, X, Y)
        self.Val = tk.StringVar()
        self.Val.set('')
        self.EntryVal = tk.Entry(container, width=W, font=Font, textvariable=self.Val)
        container.create_window(int(X * coef), Y, anchor=tk.NW, window=self.EntryVal)


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

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

        self.ListCanvasMenu = []
        self.ListImgMenu = []
        self.ListMenu = []

        self.MenuPara, wsize, hsize, self.CanvasMenuPara, self.ImgMenuPara = CanInWindow(
            'Media/FrmGraph/BarreMenu/Onglets/', RX, RY, self.CanvasMenu,
            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=FontLabel(sizefont), anchor=tk.CENTER)

        self.MenuModel, wsize, hsize, self.CanvasMenuModel, self.ImgMenuModel = CanInWindow(
            'Media/FrmGraph/BarreMenu/Onglets/', RX, RY, self.CanvasMenu,
            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=FontLabel(sizefont), anchor=tk.CENTER)

        self.MenuTab, wsize, hsize, self.CanvasMenuTab, self.ImgMenuTab = CanInWindow(
            'Media/FrmGraph/BarreMenu/Onglets/', RX, RY, self.CanvasMenu,
            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=FontLabel(sizefont), anchor=tk.CENTER)

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

            self.ListCanvasMenu[i].bind('<Motion>', GestEvt)
            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 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])