import os
from enum import Enum, auto
from math import floor
from typing import Optional

import pygame

from src.config import Config
from src.graph.graph import Graph
from src.image_handler import ImageHandler
from src.utils.paths import CONFIG_DIR, CACHE_DIR


class Editor:
    APP_NAME: str = "lycacraft-paths"
    APP_AUTHOR: str = "Lycacraft"
    WIDTH: int = 800
    HEIGHT: int = 600
    MAP_SIZE: int = 1024
    CONFIG_PATH: str = os.path.join(CONFIG_DIR, "config.json")
    MAPS_DIR: str = os.path.join(CACHE_DIR, "maps")
    AUTOSAVE_PATH: str = os.path.join(CACHE_DIR, "AUTOSAVE.txt")
    AUTOSAVE_EVENT: int = pygame.event.custom_type()
    ZOOMS: tuple[float] = tuple(2**p for p in range(-6, 7))
    CROSSHAIR_SIZE: int = 10

    EDGE_TYPE_KEYS: dict[int, str] = {
        pygame.K_p: "path",
        pygame.K_n: "narrow_path",
        pygame.K_f: "ferry",
        pygame.K_b: "boat",
        pygame.K_r: "rails"
    }

    NODE_TYPE_KEYS: list[int] = [
        pygame.K_0,
        pygame.K_1,
        pygame.K_2,
        pygame.K_3,
        pygame.K_4
    ]

    def __init__(self):
        pygame.init()
        self.config: Config = Config(self.CONFIG_PATH)
        self.width: int = self.WIDTH
        self.height: int = self.HEIGHT
        self.win: pygame.Surface = pygame.display.set_mode([self.width, self.height], pygame.RESIZABLE)
        pygame.display.set_caption("Lycacraft Map Editor")
        self.center: list[int] = [0, 0]
        self.zoom_i: int = self.ZOOMS.index(1)
        self.zoom: float = self.ZOOMS[self.zoom_i]
        self.running: bool = False
        self.image_handler: ImageHandler = ImageHandler(self.MAPS_DIR, self.MAP_SIZE, self.config.CACHE_TTL)
        self.clock: pygame.time.Clock = pygame.time.Clock()
        self.left_drag_pos: Optional[tuple[int, int]] = None
        self.mid_drag_pos: Optional[tuple[int, int]] = None
        self.font: pygame.font.Font = pygame.font.SysFont("Ubuntu", 20)
        self.loading_font: pygame.font.Font = pygame.font.SysFont("Ubuntu", 30)
        self.zooms_texts: list[pygame.Surface] = []
        for zoom in self.ZOOMS:
            txt = str(zoom)
            if zoom < 1:
                txt = f"1/{int(1/zoom):d}"
            self.zooms_texts.append(self.font.render(txt, True, (255, 255, 255)))
        self.is_renaming_node: bool = False
        self.state: State = State.STOPPING
        self.graph = Graph()
        self.typing_text: str = ""
        self.node_radius: int = 5
        self.line_size: int = 3
        self.edge_detect_radius: int = 3 * self.line_size
        self.selected_nodes: list[int] = []
        self.selected_edges: list[int] = []
        self.previously_created_nodes: list[int] = []
        self.selection_rectangle: Optional[list[tuple[int, int], tuple[int, int]]] = None
        self.original_move_pos: Optional[tuple[int, int]] = None
        self.move_old_poses: Optional[dict[int, tuple[int, int]]] = None
        self.dirty: bool = False
        self.loading_bg: pygame.Surface = pygame.Surface([self.width, self.height])
        pygame.time.set_timer(self.AUTOSAVE_EVENT, self.config.AUTOSAVE_INTERVAL)

        if os.path.exists(self.AUTOSAVE_PATH):
            self.load(self.AUTOSAVE_PATH, False)
            self.dirty = True
        elif self.config.LAST_OPENED_FILE != "":
            self.load(self.config.LAST_OPENED_FILE)


    # =========================
    # EVENTS
    # =========================

    def mainloop(self) -> None:
        self.state = State.LOADING
        while self.state != State.STOPPING:
            caption = f"Lycacraft Map Editor - {self.clock.get_fps():.2f}fps - {self.image_handler.size} images"
            if self.dirty:
                caption += " (unsaved)"
            pygame.display.set_caption(caption)
            self.process_events()
            if self.state == State.LOADING:
                self.render_loading()
                if not self.image_handler.loading:
                    self.state = State.RUNNING
            elif self.state == State.RUNNING:
                if self.selection_rectangle is not None:
                    self.expand_selection_rect()
                if self.original_move_pos is not None:
                    self.move_poses()
                self.render()
                self.image_handler.clean()
            self.clock.tick(30)

    def quit(self) -> None:
        if self.dirty:
            self.save(self.AUTOSAVE_PATH, False)
        self.state = State.STOPPING

    def process_events(self) -> None:
        events = pygame.event.get()

        keys = pygame.key.get_pressed()
        for event in events:
            if event.type == pygame.QUIT:
                self.quit()
            elif event.type == pygame.WINDOWRESIZED:
                self.width = event.x
                self.height = event.y
            elif event.type == pygame.KEYDOWN:
                if self.is_renaming_node:
                    if event.key == pygame.K_ESCAPE:
                        self.is_renaming_node = False
                        self.typing_text = ""
                    elif event.key == pygame.K_RETURN:
                        self.rename_nodes()
                    elif event.key == pygame.K_BACKSPACE:
                        self.typing_text = self.typing_text[:-1]
                    else:
                        self.typing_text += event.unicode
                else:
                    if event.key == pygame.K_ESCAPE:
                        if self.selected_nodes != [] or self.selected_edges != []:
                            self.clear_selection()
                            self.previously_created_nodes = []
                        else:
                            self.quit()
                    elif event.key == pygame.K_PAGEUP:
                        self.zoom_in()
                    elif event.key == pygame.K_PAGEDOWN:
                        self.zoom_out()
                    elif event.key == pygame.K_BACKSPACE:
                        self.deleted_selected_objects()
                    elif event.key == pygame.K_s and event.mod & (pygame.KMOD_CTRL | pygame.KMOD_META):
                        self.save()
                    elif event.key == pygame.K_l and event.mod & (pygame.KMOD_CTRL | pygame.KMOD_META):
                        self.load()
                    elif event.key == pygame.K_RETURN:
                        if len(self.selected_nodes) > 0:
                            self.typing_text = ""
                            if len(self.selected_nodes) == 1:
                                self.typing_text = self.graph.nodes[self.selected_nodes[0]].name
                            self.is_renaming_node = True
                    elif event.key == pygame.K_HOME:
                        self.center = [0, 0]
                    elif event.key == pygame.K_F5:
                        self.reload()
                    elif event.key in self.EDGE_TYPE_KEYS.keys():
                        self.change_edge_types(self.EDGE_TYPE_KEYS[event.key])
                    elif event.key in self.NODE_TYPE_KEYS:
                        self.change_node_types(self.NODE_TYPE_KEYS.index(event.key))
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_m:
                    if self.original_move_pos is not None:
                        self.reset_move_poses()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 2:
                    self.mid_drag_pos = event.pos
                elif event.button == 1:
                    if keys[pygame.K_LCTRL]:
                        self.left_drag_pos = event.pos
                    elif keys[pygame.K_LALT]:
                        self.create_selection_rect(keys[pygame.K_LSHIFT] or keys[pygame.K_RSHIFT])
                    elif keys[pygame.K_m]:
                        self.original_move_pos = event.pos
                        self.start_moving()
                    else:
                        self.select_object(keys[pygame.K_LSHIFT] or keys[pygame.K_RSHIFT])
                elif event.button == 3:
                    self.create_node(self.screen_to_world(event.pos[0], event.pos[1]))
                elif event.button == 4:
                    self.zoom_in()
                elif event.button == 5:
                    self.zoom_out()
            elif event.type == pygame.MOUSEBUTTONUP:
                if event.button == 2:
                    self.mid_drag_pos = None
                elif event.button == 1:
                    if keys[pygame.K_LCTRL]:
                        self.left_drag_pos = None
                    elif keys[pygame.K_m] and self.original_move_pos is not None:
                        self.confirm_move_poses()
                    elif self.selection_rectangle is not None:
                        self.release_selection_rect(keys[pygame.K_LSHIFT] or keys[pygame.K_RSHIFT])
            elif event.type == self.AUTOSAVE_EVENT:
                if self.dirty:
                    self.save(self.AUTOSAVE_PATH, False)

        if keys[pygame.K_LEFT]:
            self.center[0] -= 4 / self.zoom
        if keys[pygame.K_RIGHT]:
            self.center[0] += 4 / self.zoom
        if keys[pygame.K_UP]:
            self.center[1] -= 4 / self.zoom
        if keys[pygame.K_DOWN]:
            self.center[1] += 4 / self.zoom

        mbtns = pygame.mouse.get_pressed()
        mpos = pygame.mouse.get_pos()
        if mbtns[1] or (mbtns[0] and keys[pygame.K_LCTRL]):
            drag_pos = self.mid_drag_pos if mbtns[1] else self.left_drag_pos
            dx = mpos[0] - drag_pos[0]
            dy = mpos[1] - drag_pos[1]
            self.center[0] -= dx / self.zoom
            self.center[1] -= dy / self.zoom
            if mbtns[0] and keys[pygame.K_LCTRL]:
                self.left_drag_pos = mpos
            if mbtns[1]:
                self.mid_drag_pos = mpos


    # =========================
    # RENDERING
    # =========================

    def render(self) -> None:
        self.win.fill((50, 50, 50))
        off_x = (self.center[0] * self.zoom) % self.MAP_SIZE
        off_y = (self.center[1] * self.zoom) % self.MAP_SIZE

        w2 = self.width / 2
        h2 = self.height / 2

        # In game top-left / bottom-right corners
        x0 = floor(self.center[0] - w2 / self.zoom)
        y0 = floor(self.center[1] - h2 / self.zoom)
        x1 = floor(self.center[0] + w2 / self.zoom)
        y1 = floor(self.center[1] + h2 / self.zoom)

        # Top-left / bottom-right maps
        mx0 = floor(x0 * self.zoom / self.MAP_SIZE)
        my0 = floor(y0 * self.zoom / self.MAP_SIZE)
        mx1 = floor(x1 * self.zoom / self.MAP_SIZE)
        my1 = floor(y1 * self.zoom / self.MAP_SIZE)

        h_maps = mx1 - mx0 + 1
        v_maps = my1 - my0 + 1
        cx = floor(self.center[0] * self.zoom / self.MAP_SIZE)
        cy = floor(self.center[1] * self.zoom / self.MAP_SIZE)
        ox = w2 + (mx0 - cx) * self.MAP_SIZE - off_x
        oy = h2 + (my0 - cy) * self.MAP_SIZE - off_y

        for y in range(v_maps):
            for x in range(h_maps):
                map_image = self.image_handler.get_for_pos(mx0 + x, my0 + y, self.zoom)
                if map_image is None:
                    continue
                self.win.blit(map_image, [
                    ox + x * self.MAP_SIZE,
                    oy + y * self.MAP_SIZE
                ])

        self.render_graph()

        self.render_selection_rect()

        pygame.draw.line(self.win, (150, 150, 150), [w2 - self.CROSSHAIR_SIZE, h2], [w2 + self.CROSSHAIR_SIZE, h2])
        pygame.draw.line(self.win, (150, 150, 150), [w2, h2 - self.CROSSHAIR_SIZE], [w2, h2 + self.CROSSHAIR_SIZE])
        self.render_zoom_slider()

        mpos = pygame.mouse.get_pos()
        world_x, world_z = self.screen_to_world(*mpos)
        mouse_txt = self.font.render(f"x: {world_x} / z: {world_z}", True, (255, 255, 255))
        pygame.draw.rect(self.win, (80, 80, 80), [0, 0, mouse_txt.get_width() + 10, mouse_txt.get_height() + 10])
        self.win.blit(mouse_txt, [5, 5])

        if self.is_renaming_node:
            self.render_node_renamer()

        pygame.display.flip()

    def render_zoom_slider(self) -> None:
        zoom_r = self.height / 80
        zoom_space = zoom_r * 4
        zoom_height = zoom_space * (len(self.ZOOMS) - 1)
        zoom_h_margin = self.width * 0.02
        zoom_v_margin = self.height * 0.05
        zoom_x = self.width - zoom_h_margin
        zoom_y = self.height - zoom_v_margin - zoom_height
        zoom_width = max(s.get_width() for s in self.zooms_texts) + 2 * zoom_r + 5
        pygame.draw.rect(self.win, (80, 80, 80), [
            zoom_x + zoom_r - zoom_width - 5,
            zoom_y - zoom_r - 5,
            zoom_width + 10,
            zoom_height + 2 * zoom_r + 10
        ])
        pygame.draw.line(self.win, (255, 255, 255), [zoom_x, zoom_y], [zoom_x, zoom_y + zoom_height])
        for i, txt in enumerate(self.zooms_texts):
            y = zoom_y + zoom_height - i * zoom_space
            col = (255, 0, 0) if i == self.zoom_i else (255, 255, 255)
            pygame.draw.circle(self.win, col, [zoom_x, y], zoom_r)
            self.win.blit(txt, [zoom_x - txt.get_width() - zoom_r - 5, y - txt.get_height() / 2])

    def render_loading(self) -> None:
        self.win.fill((0, 0, 0))
        self.win.blit(self.loading_bg, [0, 0])
        count = self.image_handler.count
        total = self.image_handler.total
        txt = self.loading_font.render(f"Loading maps - {count}/{total}", True, (255, 255, 255))

        width = self.width * 0.6
        height = self.height * 0.05
        w2 = self.width / 2
        h2 = self.height / 2
        x0 = w2 - width / 2
        y0 = h2 - height / 2
        loaded_width = 0 if total == 0 else width * count / total
        pygame.draw.rect(self.win, (160, 160, 160), [x0, y0, width, height])
        pygame.draw.rect(self.win, (90, 250, 90), [x0, y0, loaded_width, height])
        self.win.blit(txt, [w2 - txt.get_width() / 2, y0 - txt.get_height() - 5])

        pygame.display.flip()

    def render_node_renamer(self) -> None:
        width = self.width / 2
        height = self.height / 2
        x0 = (self.width - width) / 2
        y0 = (self.height - height) / 2

        line_height = height / 6

        nc_txt = self.loading_font.render("RENAME NODE", True, (255, 255, 255))
        name_txt = self.loading_font.render("New name:", True, (255, 255, 255))
        txt = self.loading_font.render(self.typing_text, True, (255, 255, 255))

        pygame.draw.rect(self.win, (0, 0, 0), [x0, y0, width, height])
        self.win.blit(nc_txt, [self.width / 2 - nc_txt.get_width() / 2, y0 + line_height])
        self.win.blit(name_txt, [self.width / 2 - name_txt.get_width() / 2, y0 + 3 * line_height])
        self.win.blit(txt, [self.width / 2 - txt.get_width() / 2, y0 + 4 * line_height])

    def render_graph(self) -> None:
        self.render_edges()
        self.render_nodes()

    def render_edges(self) -> None:
        hover_index, is_node = self.get_hover_object()
        for edge in self.graph.edges:
            node_1, node_2 = self.graph.get_edge_nodes(edge)
            color = self.graph.TYPE_COLORS[edge.type]
            start = self.world_to_screen(node_1.x, node_1.z)
            end = self.world_to_screen(node_2.x, node_2.z)
            if not is_node and edge.index == hover_index:
                pygame.draw.line(self.win, (0, 0, 0), start, end, self.edge_detect_radius)
            elif edge.index in self.selected_edges:
                pygame.draw.line(self.win, (255, 255, 255), start, end, self.edge_detect_radius)
            pygame.draw.line(self.win, color, start, end, self.line_size)

    def render_nodes(self) -> None:
        hover_index, is_node = self.get_hover_object()
        for node in self.graph.nodes:
            blitpos = self.world_to_screen(node.x, node.z)
            color = self.graph.TYPE_COLORS[node.type]
            if is_node and node.index == hover_index:
                self.render_hover_node(node.index)
            elif node.index in self.selected_nodes:
                pygame.draw.circle(self.win, (255, 255, 255), (blitpos[0], blitpos[1]), self.node_radius + self.line_size)
            pygame.draw.circle(self.win, color, (blitpos[0], blitpos[1]), self.node_radius)

    def render_hover_node(self, node_index: int) -> None:
        node = self.graph.nodes[node_index]
        txt = self.loading_font.render(node.name, True, (255, 255, 255))
        node_pos = self.world_to_screen(node.x, node.z)
        xpos = node_pos[0] - txt.get_width() - self.node_radius * (2 ** -0.5)
        ypos = node_pos[1] - txt.get_height() - self.node_radius * (2 ** -0.5)
        pygame.draw.rect(self.win, (0, 0, 0), pygame.Rect(xpos, ypos, txt.get_width(), txt.get_height()))
        self.win.blit(txt, [xpos, ypos])
        pygame.draw.circle(self.win, (0, 0, 0), (node_pos[0], node_pos[1]), self.node_radius + self.line_size)

    def render_selection_rect(self) -> None:
        rect = self.selection_rectangle
        if rect is not None:
            left = min(rect[0][0], rect[1][0])
            top = min(rect[0][1], rect[1][1])
            width = abs(rect[0][0] - rect[1][0])
            height = abs(rect[0][1] - rect[1][1])
            pygame.draw.rect(self.win, (32, 32, 32), pygame.Rect(left, top, width, height), self.line_size)


    # =========================
    # ZOOMING
    # =========================

    def set_zoom(self, zoom_i: int) -> None:
        self.zoom_i = max(0, min(len(self.ZOOMS) - 1, zoom_i))
        self.zoom = self.ZOOMS[self.zoom_i]

    def zoom_in(self) -> None:
        self.set_zoom(self.zoom_i + 1)

    def zoom_out(self) -> None:
        self.set_zoom(self.zoom_i - 1)


    # =========================
    # SELECTION
    # =========================

    def select_object(self, shifting: bool = False) -> None:
        hover_index, is_node = self.get_hover_object()
        
        self.previously_created_nodes = []

        if is_node:
            self.select_node(hover_index, shifting)
        elif hover_index != -1:
            self.select_edge(hover_index, shifting)
        else:
            self.clear_selection()
    
    def select_node(self, node: int, shifting: bool = False) -> None:
        if shifting:
            if node in self.selected_nodes:
                self.selected_nodes.remove(node)
                return
            if node != -1:
                self.selected_nodes.append(node)
            return
        
        if node in self.selected_nodes:
            self.clear_selection()
            self.selected_nodes.append(node)
            return
        
        if node != -1:
            for sel_node in self.selected_nodes:
                self.link_nodes(sel_node, node)
        self.selected_nodes = [] if node == -1 else [node]
        self.selected_edges = []

    def select_edge(self, edge: int, shifting: bool = False) -> None:
        if shifting:
            if edge in self.selected_edges:
                self.selected_edges.remove(edge)
                return
            if edge != -1:
                self.selected_edges.append(edge)
            return
        
        if edge in self.selected_edges:
            self.clear_selection()
            self.selected_edges.append(edge)
            return
        self.selected_edges = [] if edge == -1 else [edge]
        self.selected_nodes = []

    def clear_selection(self) -> None:
        self.selected_nodes = []
        self.selected_edges = []

    def clear_node_selection(self) -> None:
        self.selected_nodes = []

    def clear_edge_selection(self) -> None:
        self.selected_edges = []

    def create_selection_rect(self, shifting: bool = False):
        if not shifting:
            self.clear_selection()
            self.previously_created_nodes = []
        mouse_pos = pygame.mouse.get_pos()
        self.selection_rectangle = [mouse_pos, mouse_pos]

    def expand_selection_rect(self):
        self.selection_rectangle[1] = pygame.mouse.get_pos()

    def release_selection_rect(self, shifting: bool = False):
        if not shifting:
            self.clear_selection()
        self.previously_created_nodes = []
        rect = self.selection_rectangle
        left = min(rect[0][0], rect[1][0])
        top = min(rect[0][1], rect[1][1])
        right = max(rect[0][0], rect[1][0])
        bottom = max(rect[0][1], rect[1][1])
        for node in self.graph.nodes:
            pos = self.world_to_screen(node.x, node.z)
            if left <= pos[0] <= right and top <= pos[1] <= bottom:
                if node.index not in self.selected_nodes:
                    self.selected_nodes.append(node.index)
        for edge in self.graph.edges:
            pos = self.world_to_screen(*self.graph.get_edge_center(edge.index))
            if left <= pos[0] <= right and top <= pos[1] <= bottom:
                if edge.index not in self.selected_edges:
                    self.selected_edges.append(edge.index)
        self.selection_rectangle = None


    # =========================
    # HOVERING
    # =========================

    def get_hovering_nodes(self) -> tuple[list[int], list[float]]:
        hovering = []
        dists = []
        mouse_pos = pygame.mouse.get_pos()

        for node in self.graph.nodes:
            dist = self.get_node_distance(node.index, mouse_pos[0], mouse_pos[1])
            if dist < self.node_radius:
                hovering.append(node.index)
                dists.append(dist)
        
        return hovering, dists
    
    def get_hover_node(self) -> int:
        hover_nodes, distances = self.get_hovering_nodes()
        return -1 if len(hover_nodes) == 0 else hover_nodes[distances.index(min(distances))]
    
    def get_hovering_edges(self) -> tuple[list[int], list[float]]:
        hovering = []
        dists = []
        mouse_pos = pygame.mouse.get_pos()

        for edge in self.graph.edges:
            dist = self.get_edge_distance(edge.index, mouse_pos[0], mouse_pos[1])
            if dist < self.edge_detect_radius:
                hovering.append(edge.index)
                dists.append(dist)
        
        return hovering, dists
    
    def get_hover_edge(self) -> int:
        hover_edges, distances = self.get_hovering_edges()
        return -1 if len(hover_edges) == 0 else hover_edges[distances.index(min(distances))]
    
    def get_hover_object(self) -> tuple[int, bool]:
        node = self.get_hover_node()
        if node != -1:
            return node, True
        
        edge = self.get_hover_edge()
        if edge != -1:
            return edge, False
        
        return -1, False


    # =========================
    # CREATION
    # =========================

    def link_nodes(self, node_1: int, node_2: int) -> None:
        if not self.graph.edge_exists(node_1, node_2):
            self.create_edge(node_1, node_2)

    def create_node(self, pos: tuple[int, int], typing_text: str = "") -> None:
        self.dirty = True
        self.graph.add_node(pos[0], pos[1], typing_text, type=self.get_node_type())
        if len(self.selected_nodes) == 1:
            self.previously_created_nodes.append(self.selected_nodes[0])
        self.select_node(self.graph.number_of_nodes() - 1)

    def create_edge(self, node_1: int, node_2: int) -> None:
        self.dirty = True
        self.graph.add_edge(node_1, node_2, type=self.get_edge_type())

    def get_edge_type(self) -> str:
        type = ""
        for key, value in self.EDGE_TYPE_KEYS.items():
            if pygame.key.get_pressed()[key]:
                type = value
                break
        return type

    def get_node_type(self) -> int:
        type = 0
        for i in range(len(self.NODE_TYPE_KEYS)):
            if pygame.key.get_pressed()[self.NODE_TYPE_KEYS[i]]:
                type = i
                break
        return type


    # =========================
    # EDITION
    # =========================

    def rename_nodes(self) -> None:
        self.dirty = True
        for node in self.selected_nodes:
            self.graph.nodes[node].rename_node(self.typing_text)
        self.typing_text = ""
        self.is_renaming_node = False

    def start_moving(self):
        self.move_old_poses = {}
        for node_index in self.selected_nodes:
            node = self.graph.nodes[node_index]
            self.move_old_poses[node_index] = (node.x, node.z)

    def move_poses(self):
        mouse_pos = pygame.mouse.get_pos()
        start_pos = self.original_move_pos
        delta_x = mouse_pos[0] - start_pos[0]
        delta_z = mouse_pos[1] - start_pos[1]
        for node_index in self.move_old_poses.keys():
            node = self.graph.nodes[node_index]
            old_pos = self.move_old_poses[node_index]
            node.x = old_pos[0] + delta_x
            node.z = old_pos[1] + delta_z

    def reset_move_poses(self):
        self.original_move_pos = None
        for node_index in self.move_old_poses.keys():
            node = self.graph.nodes[node_index]
            old_pos = self.move_old_poses[node_index]
            node.x = old_pos[0]
            node.z = old_pos[1]
        self.move_old_poses = None

    def confirm_move_poses(self):
        self.dirty = True
        self.original_move_pos = None
        self.move_old_poses = None

    def change_edge_types(self, type: str = "path"):
        self.dirty = True
        for edge in self.selected_edges:
            self.graph.set_edge_type(edge, type)

    def change_node_types(self, type: int = 0):
        self.dirty = True
        for node_index in self.selected_nodes:
            node = self.graph.nodes[node_index]
            node.set_type(type)

    def deleted_selected_objects(self):
        self.dirty = True
        edges_to_delete = [self.graph.edges[i] for i in self.selected_edges]
        nodes_to_delete = [self.graph.nodes[i] for i in self.selected_nodes]
        for edge in edges_to_delete:
            self.graph.delete_edge(edge)
        for node in nodes_to_delete:
            self.graph.delete_node(node)
        self.clear_selection()
        n = len(self.previously_created_nodes)
        if n != 0:
            self.selected_nodes.append(self.previously_created_nodes[n - 1])
            self.previously_created_nodes.pop()


    # =========================
    # CALCULATION
    # =========================

    def screen_to_world(self, x: int, y: int) -> tuple[int, int]:
        w2 = self.width / 2
        h2 = self.height / 2
        world_x = floor((x - w2) / self.zoom + self.center[0])
        world_z = floor((y - h2) / self.zoom + self.center[1])

        return int(world_x), int(world_z)

    def world_to_screen(self, world_x: int, world_z: int) -> tuple[int, int]:
        w2 = self.width / 2
        h2 = self.height / 2
        screen_x = (world_x - self.center[0]) * self.zoom + w2
        screen_y = (world_z - self.center[1]) * self.zoom + h2

        return int(screen_x), int(screen_y)

    def get_edge_distance(self, edge_i: int, px: int, pz: int) -> float:
        start_n, end_n = self.graph.get_edge_nodes(self.graph.edges[edge_i])
        start_p = self.world_to_screen(start_n.x, start_n.z)
        end_p = self.world_to_screen(end_n.x, end_n.z)

        edge_vec = (end_p[0] - start_p[0], end_p[1] - start_p[1])
        start_vec = (px - start_p[0], pz - start_p[1])

        edge_vec_len = (edge_vec[0] ** 2 + edge_vec[1] ** 2) ** 0.5

        if edge_vec_len == 0:
            return self.get_node_distance(start_n.index, px, pz)

        scal_prod = start_vec[0] * edge_vec[0] + start_vec[1] * edge_vec[1]

        proj_len = scal_prod / edge_vec_len

        if proj_len < 0:
            return self.get_node_distance(start_n.index, px, pz)
        if proj_len > edge_vec_len:
            return self.get_node_distance(end_n.index, px, pz)
        return abs((edge_vec[0] * start_vec[1] - edge_vec[1] * start_vec[0]) / edge_vec_len)

    def get_node_distance(self, node_i: int, px: int, pz: int) -> float:
        node = self.graph.nodes[node_i]
        node_pos = self.world_to_screen(node.x, node.z)
        return ((px - node_pos[0]) ** 2 + (pz - node_pos[1]) ** 2) ** 0.5



    # SAVING

    def save(self, path: Optional[str] = None, save_config: bool = True) -> None:
        last_path = self.config.LAST_OPENED_FILE
        if path is None:
            path = input(f"Save as ({last_path}): ")
            if len(path.strip()) == 0:
                path = last_path

        self.graph.save(path)
        if save_config:
            self.config.LAST_OPENED_FILE = path
            self.config.save()
            if os.path.exists(self.AUTOSAVE_PATH):
                os.remove(self.AUTOSAVE_PATH)
        self.dirty = False

    def load(self, path: Optional[str] = None, save_config: bool = True) -> None:
        last_path = self.config.LAST_OPENED_FILE
        if path is None:
            path = input(f"Load from ({last_path}): ")
            if len(path.strip()) == 0:
                path = last_path

        if os.path.exists(path):
            self.graph = Graph.load(path)
            if save_config:
                self.config.LAST_OPENED_FILE = path
                self.config.save()
            self.dirty = False

    def reload(self) -> None:
        self.state = State.LOADING
        self.loading_bg = self.win.copy()
        del self.image_handler
        self.image_handler = ImageHandler(self.MAPS_DIR, self.MAP_SIZE, self.config.CACHE_TTL)


class State(Enum):
    STOPPING = auto()
    LOADING = auto()
    RUNNING = auto()
