import os
import math
import tkinter
from decimal import Decimal

class WalkFigures(pynebv.Plugin):
    location = ['file_panel/item_menu']
    contact = 'ncs'
    label = 'Walk Figures'
    def centering_tkinter_root(self, event):
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_width = self.root.winfo_width()
        window_height = self.root.winfo_height()
        x = screen_width / 2 - window_width /2
        y = screen_height / 2 - window_height / 2
        self.root.geometry("+%d+%d" % (x, y))
    def quit_dialog(self):
        self.quit_now = True
        self.root.destroy()
    def show_next_dialog(self):
        self.quit_now = False
        self.root = tkinter.Tk()
        self.root.title(u"Figure Walk")
        self.root.geometry("200x50")
        self.root.attributes("-topmost", True or False)
        self.root.bind("<Visibility>", self.centering_tkinter_root)
        button = tkinter.Button(self.root, text="Next", command=lambda: self.root.destroy())
        button.pack()
        button = tkinter.Button(self.root, text="Quit", command=self.quit_dialog)
        button.pack()
        self.root.mainloop()
    def show_target_ascendants(self, item):
        print(f"aa {item.display_name[:15]}")
        if item.display_name[:15] == "Walk:Target*-- ":
            item.display = True
            descendants = item.descendants()
            if descendants:
                descendants.display = True
            return True
        has_visible = False
        children = item.descendants('', True)
        for child in children:
            if self.show_target_ascendants(child):
                item.display = True
                has_visible = True
        return has_visible
    def show_targets(self, targets):
        for target in targets:
            target.display_name = f"Walk:Target*-- {target.display_name}"
        list = pynebv.file.list()
        for top in list:
            if self.show_target_ascendants(top):
                top.display = True
        for target in targets:
            target.display_name = target.display_name[15:]
    def exec(self, context):
        if hasattr(pynebv, 'error_mode'):
            raise RuntimeError('Error mode is already set')
        all_items = pynebv.file.items()
        visibles = pynebv.EbvItemList([item for item in all_items if item.display])
        not_visibles = pynebv.EbvItemList([item for item in all_items if not item.display])
        targets = context['items']
        if visibles:
            visibles.display = False
        self.show_targets(targets)
        polygons = pynebv.figure.polygons()
        if visibles:
            visibles.display = True
        if not_visibles:
            not_visibles.display = False
        origin_area = pynebv.screen.get_area()
        for polygon in polygons:
            area = None
            for point in polygon.points:
                if area is None:
                    area = [point.x, point.y, point.x, point.y]
                if point.x < area[0]:
                    area[0] = point.x
                elif point.x > area[2]:
                    area[2] = point.x
                if point.y < area[1]:
                    area[1] = point.y
                elif point.y > area[3]:
                    area[3] = point.y
            margin = 10
            width = area[2] - area[0]
            height = area[3] - area[1]
            max_size = width if width > height else height
            if max_size > 0:
                margin = max_size
            area[0] -= margin
            area[1] -= margin
            area[2] += margin
            area[3] += margin
            # crafted to avoid exponential notation
            str_array = [f"{value:.10f}" for value in area]
            print(area)
            print(str_array)
            pynebv.screen.set_area(str_array)
            self.show_next_dialog()
            if self.quit_now:
                break
        pynebv.screen.set_area(origin_area)


