from AppliDef import *


class FrmModifCircuit(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, RatioY2, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.RatioY2 = RatioY2
        self.X1Mouse = 0
        self.Y1Mouse = 0
        self.X2Mouse = 0
        self.Y2Mouse = 0
        self.XZT = 0
        self.YZT = 0
        self.X0ImgCircuit = 0
        self.X1ImgCircuit = 0
        self.Y0ImgCircuit = 0
        self.Y1ImgCircuit = 0
        self.cropped_img = None
        self.ZoneRecadrage = None
        self.RecadreImg = False
        self.ActionRecadreImg = False
        self.PathFilejpgToOpen = ''
        self.Nimage = 0
        self.InfoAction = False
        self.ListInfoAction = ['Ouvrir une image', "Recadrer l'image", "Supprimer l'image", 'Annuler', 'Rétablir']
        self.TooltipAction = None

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

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmModifCircuit/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.004)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.057)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        self.ListBtn = []
        SizeFont = int(ConfigResolution(self.MainAppli.MainAppli.Nconfig, 'MC'))

        self.LabelCircuit = LabelInCanvas(self.CanvasFrmFond, " Modifier l'image du Circuit ", '#F4F4F4',
                                          FontLabel(SizeFont), int(self.SX * 0.005), int(self.SY * 0.015))
        self.BtnOpen = BtnAction(self.CanvasFrmFond, int(self.SX * 0.13), int(self.SY * 0.028), self.RatioX,
                                 self.RatioY2, 'Media/FrmModifCircuit/BtnOuvrir/')
        self.BtnOpen.CanvasBtn.bind('<ButtonRelease-1>', self.OpenImage)
        self.ListBtn.append(self.BtnOpen)

        self.BtnRecadre = BtnAction(self.CanvasFrmFond, int(self.SX * 0.16), int(self.SY * 0.028), self.RatioX,
                                    self.RatioY2, 'Media/FrmModifCircuit/BtnRecadrer/')
        self.BtnRecadre.CanvasBtn.bind('<ButtonRelease-1>', self.RecadrerImage)
        self.ListBtn.append(self.BtnRecadre)

        self.BtnSupImg = BtnAction(self.CanvasFrmFond, int(self.SX * 0.19), int(self.SY * 0.028), self.RatioX,
                                   self.RatioY2, 'Media/FrmModifCircuit/BtnSupp/')
        self.BtnSupImg.CanvasBtn.bind('<ButtonRelease-1>', self.SupprimImage)
        self.ListBtn.append(self.BtnSupImg)

        self.BtnRetour = BtnAction(self.CanvasFrmFond, int(self.SX * 0.22), int(self.SY * 0.028), self.RatioX,
                                   self.RatioY2, 'Media/FrmModifCircuit/BtnRetour/')
        self.BtnRetour.CanvasBtn.bind('<ButtonRelease-1>', self.RetourImage)
        self.ListBtn.append(self.BtnRetour)

        self.BtnAvance = BtnAction(self.CanvasFrmFond, int(self.SX * 0.25), int(self.SY * 0.028), self.RatioX,
                                   self.RatioY2, 'Media/FrmModifCircuit/BtnAvance/')
        self.BtnAvance.CanvasBtn.bind('<ButtonRelease-1>', self.AvanceImage)
        self.ListBtn.append(self.BtnAvance)

        for i in range(len(self.ListBtn)):
            def GestEvt(_, j=i):
                return self.MotionBtn(j)

            self.ListBtn[i].CanvasBtn.bind('<Motion>', GestEvt)

        self.ImgCircuitModif = []
        self.ImgJPG = []
        self.img = Image.open(self.MainAppli.MainAppli.ListCircuitSketchs[self.MainAppli.MainAppli.IndexFile])
        self.ImgCircuitModif.append(ImageTk.PhotoImage(self.img))
        self.ImgJPG.append(self.img)
        self.Nimage = len(self.ImgCircuitModif)
        self.CanvasImgCircuit = CanvasApp(self.CanvasFrmFond, width=self.img.size[0], height=self.img.size[1],
                                          bg='white')
        self.CanvasFrmFond.create_window(int(self.SX / 2), int(self.SY / 2), anchor=tk.CENTER,
                                         window=self.CanvasImgCircuit)
        self.wsize, self.hsize = self.img.size[0], self.img.size[1]
        self.ImgCanvasImgCircuit = self.CanvasImgCircuit.create_image(int(self.img.size[0] / 2),
                                                                      int(self.img.size[1] / 2),
                                                                      anchor=tk.CENTER,
                                                                      image=self.ImgCircuitModif[0])

        self.CanvasImgCircuit.bind("<Button-1>", self.ClicOnCanvasImgCircuit)
        self.CanvasImgCircuit.bind("<B1 - Motion>", self.DessineZoneRecadrage)

        self.BtnOK = BtnAction(self.CanvasFrmFond, int(self.SX * 0.85), int(self.SY * 0.955), self.RatioX,
                               self.RatioY2, 'Media/FrmDetails/BtnOK/')
        self.BtnOK.CanvasBtn.bind('<ButtonRelease-1>', self.ModifCircuitOK)

        self.BtnAnnul = BtnAction(self.CanvasFrmFond, int(self.SX * 0.9), int(self.SY * 0.955), self.RatioX,
                                  self.RatioY2,
                                  'Media/FrmDetails/BtnAnnul/')
        self.BtnAnnul.CanvasBtn.bind('<ButtonRelease-1>', self.ModifCircuitAnnul)

        self.MenuClicDroit = tk.Menu(self.CanvasImgCircuit, tearoff=0)
        self.MenuClicDroit.add_command(label="Valider", command=self.ValidRecadrage)
        self.MenuClicDroit.add_separator()
        self.MenuClicDroit.add_command(label="Annuler", command=self.AnnulRecadrage)

        self.CanvasImgCircuit.bind("<Button-3>", self.AffichMenuClicDroit)

        self.CanvasFrmFond.bind('<Motion>', self.MotionCanvasFrmFond)
        self.CanvasFrmFond.pack()

    def ClicOnCanvasImgCircuit(self, event):
        if self.ActionRecadreImg:
            X = event.x
            Y = event.y
            self.CanvasImgCircuit.delete(self.ZoneRecadrage)
            self.ZoneRecadrage = self.CanvasImgCircuit.create_rectangle(0, 0, 0, 0)
            if self.X0ImgCircuit < X < self.X1ImgCircuit and self.Y0ImgCircuit < Y < self.Y1ImgCircuit:
                self.X1Mouse = X
                self.Y1Mouse = Y
            else:
                self.X1Mouse = self.X0ImgCircuit
                self.Y1Mouse = self.Y0ImgCircuit

    def DessineZoneRecadrage(self, event):
        if self.ActionRecadreImg:
            X = event.x
            Y = event.y
            if self.X0ImgCircuit < X < self.X1ImgCircuit and self.Y0ImgCircuit < Y < self.Y1ImgCircuit:
                self.CanvasImgCircuit.delete(self.ZoneRecadrage)
                self.X2Mouse = X
                if self.X2Mouse > self.X1Mouse:
                    if Y > self.Y1Mouse:
                        self.Y2Mouse = self.Y1Mouse + (self.X2Mouse - self.X1Mouse) / 1.654867257
                    else:
                        self.Y2Mouse = self.Y1Mouse - (self.X2Mouse - self.X1Mouse) / 1.654867257
                else:
                    if Y > self.Y1Mouse:
                        self.Y2Mouse = self.Y1Mouse + (self.X1Mouse - self.X2Mouse) / 1.654867257
                    else:
                        self.Y2Mouse = self.Y1Mouse - (self.X1Mouse - self.X2Mouse) / 1.654867257
                self.ZoneRecadrage = self.CanvasImgCircuit.create_rectangle(self.X1Mouse, self.Y1Mouse, self.X2Mouse,
                                                                            self.Y2Mouse, width=2)

    def ModifCircuitAnnul(self, _):
        self.destroy()
        self.MainAppli.lift()

    def ModifCircuitOK(self, _):
        self.MainAppli.ImgCircuitModif = []
        self.MainAppli.ImgCircuitModif.append(self.ImgJPG[self.Nimage - 1])
        self.MainAppli.AffichImgCircuitModif()
        self.MainAppli.ModifImgCircuit = True
        self.destroy()
        self.MainAppli.lift()

    def ValidRecadrage(self):
        self.BtnRecadre.CanvasBtn.itemconfig(self.BtnRecadre.ImgCanvasBtn, image=self.BtnRecadre.ImgBtn[0])
        self.RecadreImg = True
        self.ActionRecadreImg = False
        ChangeCursor2(self.CanvasImgCircuit)
        self.CanvasImgCircuit.delete(self.ZoneRecadrage)
        area = (self.X1Mouse, self.Y1Mouse, self.X2Mouse, self.Y2Mouse)
        self.cropped_img = self.ImgJPG[self.Nimage - 1].crop(area)
        self.ImgCircuitModif.append(ImageTk.PhotoImage(self.cropped_img))
        self.ImgJPG.append(self.cropped_img)
        self.Nimage = len(self.ImgCircuitModif)
        self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit,
                                         image=self.ImgCircuitModif[len(self.ImgCircuitModif) - 1])

    def AffichMenuClicDroit(self, event):
        if self.ActionRecadreImg:
            self.XZT = event.x
            self.YZT = event.y
            if self.X2Mouse > self.X1Mouse:
                if self.Y2Mouse > self.Y1Mouse:
                    if self.X1Mouse < self.XZT < self.X2Mouse and self.Y1Mouse < self.YZT < self.Y2Mouse:
                        self.MenuClicDroit.post(event.x_root, event.y_root)
                else:
                    if self.X1Mouse < self.XZT < self.X2Mouse and self.Y2Mouse < self.YZT < self.Y1Mouse:
                        self.MenuClicDroit.post(event.x_root, event.y_root)
            else:
                if self.Y2Mouse > self.Y1Mouse:
                    if self.X2Mouse < self.XZT < self.X1Mouse and self.Y1Mouse < self.YZT < self.Y2Mouse:
                        self.MenuClicDroit.post(event.x_root, event.y_root)
                else:
                    if self.X2Mouse < self.XZT < self.X1Mouse and self.Y2Mouse < self.YZT < self.Y1Mouse:
                        self.MenuClicDroit.post(event.x_root, event.y_root)

    def AnnulRecadrage(self):
        if self.X2Mouse > self.X1Mouse:
            if self.Y2Mouse > self.Y1Mouse:
                if self.X1Mouse < self.XZT < self.X2Mouse and self.Y1Mouse < self.YZT < self.Y2Mouse:
                    self.CanvasImgCircuit.delete(self.ZoneRecadrage)
            else:
                if self.X1Mouse < self.XZT < self.X2Mouse and self.Y2Mouse < self.YZT < self.Y1Mouse:
                    self.CanvasImgCircuit.delete(self.ZoneRecadrage)
        else:
            if self.Y2Mouse > self.Y1Mouse:
                if self.X2Mouse < self.XZT < self.X1Mouse and self.Y1Mouse < self.YZT < self.Y2Mouse:
                    self.CanvasImgCircuit.delete(self.ZoneRecadrage)
            else:
                if self.X2Mouse < self.XZT < self.X1Mouse and self.Y2Mouse < self.YZT < self.Y1Mouse:
                    self.CanvasImgCircuit.delete(self.ZoneRecadrage)
        self.X1Mouse, self.X2Mouse, self.Y1Mouse, self.Y2Mouse = 0, 0, 0, 0
        self.ActionRecadreImg = False
        ChangeCursor2(self.CanvasImgCircuit)
        self.BtnRecadre.CanvasBtn.itemconfig(self.BtnRecadre.ImgCanvasBtn, image=self.BtnRecadre.ImgBtn[0])

    def OpenImage(self, _):
        self.PathFilejpgToOpen = ''
        self.PathFilejpgToOpen = tkfiledialog.askopenfilename(title="Ouvrir un fichier",
                                                              filetypes=[('JPG files', '.jpg')])
        self.MainAppli.MainAppli.FrmData.lift()
        self.lift()
        if self.PathFilejpgToOpen != '':
            self.img = Image.open(self.PathFilejpgToOpen)
            self.img = self.img.resize((self.wsize, self.hsize), Image.ANTIALIAS)
            self.ImgCircuitModif.append(ImageTk.PhotoImage(self.img))
            self.ImgJPG.append(self.img)
            self.Nimage = len(self.ImgCircuitModif)
            self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit,
                                             image=self.ImgCircuitModif[len(self.ImgCircuitModif) - 1])

    def RecadrerImage(self, _):
        ChangeCursor(self.CanvasImgCircuit)
        self.ZoneRecadrage = self.CanvasImgCircuit.create_rectangle(0, 0, 0, 0)
        self.X0ImgCircuit = 0
        self.X1ImgCircuit = self.img.size[0]
        self.Y0ImgCircuit = 0
        self.Y1ImgCircuit = self.img.size[1]
        self.ActionRecadreImg = True

    def SupprimImage(self, _):
        self.BtnSupImg.CanvasBtn.itemconfig(self.BtnSupImg.ImgCanvasBtn, image=self.BtnSupImg.ImgBtn[0])
        self.img = Image.open('Media/CanvasDetails/Logo/NoCircuit.jpg')
        self.ImgCircuitModif.append(ImageTk.PhotoImage(self.img))
        self.ImgJPG.append(self.img)
        self.Nimage = len(self.ImgCircuitModif)
        self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit,
                                         image=self.ImgCircuitModif[len(self.ImgCircuitModif) - 1])

    def RetourImage(self, _):
        self.BtnRetour.CanvasBtn.itemconfig(self.BtnRetour.ImgCanvasBtn, image=self.BtnRetour.ImgBtn[0])
        if self.Nimage > 1:
            self.Nimage = self.Nimage - 1
            self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit, image=self.ImgCircuitModif[self.Nimage - 1])

    def AvanceImage(self, _):
        self.BtnAvance.CanvasBtn.itemconfig(self.BtnAvance.ImgCanvasBtn, image=self.BtnAvance.ImgBtn[0])
        if self.Nimage < len(self.ImgCircuitModif):
            self.Nimage = self.Nimage + 1
            self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit, image=self.ImgCircuitModif[self.Nimage - 1])

    def MotionBtn(self, i):
        self.AffichInfoAction(self.ListInfoAction[i])

    def AffichInfoAction(self, Action):
        if self.InfoAction:
            self.CanvasFrmFond.delete(self.TooltipAction)
            self.InfoAction = False

        self.TooltipAction = self.CanvasFrmFond.create_text(int(self.SX * 0.28),
                                                            int(self.SY * 0.028), anchor=tk.W, text=Action,
                                                            fill='red', font=FontLabel2(11))
        self.InfoAction = True

    def MotionCanvasFrmFond(self, _):
        if self.InfoAction:
            self.CanvasFrmFond.delete(self.TooltipAction)
            self.InfoAction = False
