# -*-coding:utf-8 -*

import tkinter as tk
from tkinter import messagebox
from tkinter import simpledialog
from pdfembannersrc import subwindows
import logging
logger = logging.getLogger()

class InterfaceEdit(tk.Toplevel):
    """
    Edition window
    """

    def __init__(self, parent, fichobj, **kwargs):
        tk.Toplevel.__init__(self, parent)
        self.transient(parent)
        self.grab_set()
        self.geometry("800x400")
        self.bind("<Return>", self.ok)

        self.fich = fichobj

        self.title("Edit {}".format(self.fich.name))

        if(self.fich.use is None):
            self.fich.use = []
        if(self.fich.order is None):
            self.fich.order = []

        self.pages = []

        self.f = tk.Frame(self, width=768, height=576, **kwargs)
        self.f.pack(fill=tk.BOTH)

        # Création de nos widgets
        self.f.columnconfigure(7, weight=1)
        self.f.rowconfigure(3, weight=1)

        info1 = tk.Label(self.f, text="Choose used pages :", fg="white", padx=20, bg="blue")
        info1.grid(row=0, column=0, columnspan=10, sticky=tk.W)
        
        tk.Button(self.f, text="Select all", command=self.selectall).grid(row=1, column=0)
        tk.Button(self.f, text="Unselect all", command=self.deselectall).grid(row=2, column=0)
        tk.Button(self.f, text="Select range", command=self.selectrange).grid(row=1, column=1)
        tk.Button(self.f, text="Unselect range", command=self.deselectrange).grid(row=2, column=1)
        tk.Button(self.f, text="Select pair", command=self.selectpair).grid(row=1, column=2)
        tk.Button(self.f, text="Unselect pair", command=self.unselectpair).grid(row=2, column=2)
        tk.Button(self.f, text="Select impair", command=self.selectimpair).grid(row=1, column=3)
        tk.Button(self.f, text="Unselect impair", command=self.unselectimpair).grid(row=2, column=3)
        tk.Button(self.f, text="Toggle", command=self.toggle).grid(row=1, column=4)
        tk.Button(self.f, text="Add blank page", command=self.addblankpage).grid(row=1, column=10)

        vsb = tk.Scrollbar(self.f, orient=tk.VERTICAL)
        vsb.grid(row=3, column=11, sticky=tk.N+tk.S)
        self.c = tk.Canvas(self.f, yscrollcommand=vsb.set)
        self.c.grid(row=3, column=0, columnspan=10, sticky="news")
        vsb.config(command=self.c.yview)
        self.frame_pages = tk.Frame(self.c)
        self.frame_pages.columnconfigure(4, weight=1)

        for e in range(self.fich.npages+self.fich.nblankpages):
            if(len(self.fich.use)<=e):
                self.fich.use.append(True)
            if(len(self.fich.order)<=e):
                self.fich.order.append(e)
            page = Page(self, e)
            self.pages.append(page)
            page.add_widgets(self.frame_pages)
        
        self.c.create_window(0, 0,  window=self.frame_pages, anchor=tk.NW)
        self.frame_pages.update_idletasks()
        self.c.config(scrollregion=self.c.bbox("all"))
        
        info1 = tk.Label(self.f, text="Options on the whole file :", fg="white", padx=20, bg="blue")
        info1.grid(row=4, column=0, columnspan=10, sticky=tk.W)
        
        tk.Button(self.f, text="Rotate", command=self.rotate).grid(row=5, column=0)
        tk.Button(self.f, text="Crop", command=self.crop).grid(row=5, column=1)
        
        tk.Button(self.f, text="Ok", command=self.ok).grid(row=6, column=10)
        
        self.message = tk.Label(self.f, text="Editing {}".format(self.fich.name))
        self.message.grid(row=7, column=0, columnspan=11, sticky=tk.W)


    def ok(self, *args):
        """
        Save and quit
        """
        self.message["text"] = "Done"
        self.quit()
        self.destroy()

    def up(self, i):
        pos = self.fich.order[i]
        if(pos>0 and pos<self.fich.npages):
            for toech in range(self.fich.npages):
                if(self.fich.order[toech]==pos-1):
                    break
            self.fich.order[i] -= 1
            self.fich.order[toech] += 1
            self.pages[i].unset_i_widgets()
            self.pages[toech].unset_i_widgets()
            self.pages[i].set_i_widgets(pos-1)
            self.pages[toech].set_i_widgets(pos)

    def down(self, i):
        pos = self.fich.order[i]
        if(pos<self.fich.npages-1):
            for toech in range(self.fich.npages):
                if(self.fich.order[toech]==pos+1):
                    break
            self.fich.order[i] += 1
            self.fich.order[toech] -= 1
            self.pages[i].unset_i_widgets()
            self.pages[toech].unset_i_widgets()
            self.pages[i].set_i_widgets(pos+1)
            self.pages[toech].set_i_widgets(pos)

    def selectall(self):
        for i in range(self.fich.npages):
            self.fich.use[i] = True
            self.pages[i].select()

    def deselectall(self):
        for i in range(self.fich.npages):
            self.fich.use[i] = False
            self.pages[i].deselect()

    def selectrange(self):
        selstr = simpledialog.askstring("Select range", "Range to select (ex 0-2;4):")
        for e1 in selstr.split(';'):
            e1 = e1.split('-')
            if(len(e1)==1 and e1[0].isdigit() and int(e1[0])>0 and int(e1[0])<=len(self.fich.use)):
                i = int(e1[0])
                self.fich.use[i-1] = True
                self.pages[i-1].select()
            elif(len(e1)==2 and e1[0].isdigit() and e1[1].isdigit()):
                i = int(e1[0])
                j = int(e1[1])
                if(i>0 and i<j and j<=len(self.fich.use)):
                    for k in range(i,j+1):
                        self.fich.use[k-1] = True
                        self.pages[k-1].select()
                else:
                    messagebox.showwarning(title="Warning", message="Some ranges could not be interpeted, skipped.")
                    logger.info("Concatenate : Select range : Could not interpret : {}".format(e1))
            else:
                messagebox.showwarning(title="Warning", message="Some ranges could not be interpeted, skipped.")
                logger.info("Concatenate : Select range : Could not interpret_ : {}".format(e1))

    def deselectrange(self):
        selstr = simpledialog.askstring("Select range", "Range to select (ex 0-2;4):")
        for e1 in selstr.split(';'):
            e1 = e1.split('-')
            if(len(e1)==1 and e1[0].isdigit() and int(e1[0])>0 and int(e1[0])<=len(self.fich.use)):
                i = int(e1[0])
                self.fich.use[i-1] = False
                self.pages[i-1].deselect()
            elif(len(e1)==2 and e1[0].isdigit() and e1[1].isdigit()):
                i = int(e1[0])
                j = int(e1[1])
                if(i>0 and i<j and j<=len(self.fich.use)):
                    for k in range(i,j+1):
                        self.fich.use[k-1] = False
                        self.pages[k-1].deselect()
                else:
                    messagebox.showwarning(title="Warning", message="Some ranges could not be interpeted, skipped.")
                    logger.info("Concatenate : Select range : Could not interpret : {}".format(e1))
            else:
                messagebox.showwarning(title="Warning", message="Some ranges could not be interpeted, skipped.")
                logger.info("Concatenate : Select range : Could not interpret_ : {}".format(e1))

    def selectpair(self):
        for i in range(self.fich.npages):
            if((i+1)%2==0):
                self.fich.use[i] = True
                self.pages[i].select()

    def selectimpair(self):
        for i in range(self.fich.npages):
            if((i+1)%2==1):
                self.fich.use[i] = True
                self.pages[i].select()

    def unselectpair(self):
        for i in range(self.fich.npages):
            if((i+1)%2==0):
                self.fich.use[i] = False
                self.pages[i].deselect()

    def unselectimpair(self):
        for i in range(self.fich.npages):
            if((i+1)%2==1):
                self.fich.use[i] = False
                self.pages[i].deselect()

    def toggle(self):
        for i in range(self.fich.npages):
            self.pages[i].Wcheck.toggle()
            self.pages[i].toggle()

    def crop(self):
        interface = subwindows.SetCrop(self, self.fich)
        logger.debug("Concatenate : Crop set")
        interface.mainloop()
        interface.destroy()
        logger.debug("Concatenate : End crop set with value {}".format(self.fich.crop))

    def rotate(self):
        interfaceRotate = subwindows.Rotate(self, self.fich)
        logger.debug("Rotate {}".format(self.fich.path))
        interfaceRotate.mainloop()
        interfaceRotate.destroy()
        logger.debug("End Rotate {} with value {}".format(self.fich.path, self.fich.rotate))

    def addblankpage(self):
        values={"nr":0, "after":[]}
        fen = subwindows.AskBlankPage(self, self.fich, values)
        fen.mainloop()
        fen.destroy()
        if(values["nr"]>0):
            added=0
            for e in values["after"]:
                e = e+added
                # Decalage vers le bas des pages suivantes
                for i in range(e,len(self.fich.order)):
                    self.pages[self.fich.order[i]].unset_i_widgets()
                    self.pages[self.fich.order[i]].set_i_widgets(i+1+values["nr"])
                # Ajout des pages blanches
                part1 = self.fich.order[:e]
                part2 = self.fich.order[e:]
                for i in range(values["nr"]):
                    self.fich.use.append(True)
                    self.fich.nblankpages+=1
                    added+=1
                    self.fich.order.append(self.fich.npages+self.fich.nblankpages-1)
                    page = Page(self, self.fich.npages+self.fich.nblankpages-1)
                    self.pages.append(page)
                    page.add_widgets(self.frame_pages)
                    page.unset_i_widgets()
                    page.set_i_widgets(e+i)
                    part1.append(self.fich.npages+self.fich.nblankpages-1)
                self.fich.order = part1 + part2
            self.frame_pages.update_idletasks()
            self.c.config(scrollregion=self.c.bbox("all"))


class Page:
    def __init__(self, parent, i):
        self.num = i
        self.parent = parent

        self.Wlabel = None
        self.Wcheck = None
        self.Wup = None
        self.Wdown = None

    def add_widgets(self, frame):
        if self.num>=self.parent.fich.npages:
            self.Wlabel = tk.Label(frame, text="Blank page")
        else:
            self.Wlabel = tk.Label(frame, text="Page {}".format(self.num+1))
        self.Wnum = tk.Label(frame, text="{}.".format(self.num+1))
        self.Wup = tk.Button(frame, text="Up", command=lambda: self.parent.up(self.num))
        self.Wdown = tk.Button(frame, text="Down", command=lambda: self.parent.down(self.num))
        self.Wcheck = tk.Checkbutton(frame, command=self.toggle)
        if(self.parent.fich.use[self.num]):
            self.select()
        else:
            self.deselect()
        self.set_i_widgets(self.parent.fich.order[self.num])

    def set_i_widgets(self, i):
        self.Wnum["text"] = "{}.".format(i+1)
        self.Wnum.grid(row=i, column=0, sticky=tk.W)
        self.Wlabel.grid(row=i, column=4)
        self.Wcheck.grid(row=i, column=1)
        self.Wup.grid(row=i, column=2)
        self.Wdown.grid(row=i, column=3)

    def unset_i_widgets(self):
        self.Wnum.grid_forget()
        self.Wlabel.grid_forget()
        self.Wcheck.grid_forget()
        self.Wup.grid_forget()
        self.Wdown.grid_forget()

    def toggle(self):
        if(self.parent.fich.use[self.num]):
            self.deselect()
            self.parent.fich.use[self.num] = False
        else:
            self.select()
            self.parent.fich.use[self.num] = True

    def select(self):
        self.Wlabel.config(fg="black")
        self.Wcheck.select()

    def deselect(self):
        self.Wlabel.config(fg="grey")
        self.Wcheck.deselect()