# -*- coding: utf-8 -*-
# gui/components/model_view/contour/contour_definition_component.py

# -*- coding: utf-8 -*-
# gui/components/model_view/_mv_grid_contour_definition.py
# Жизненный цикл определения контура + управление точками

from __future__ import annotations

from typing import TYPE_CHECKING

from error_logger import log_exception

if TYPE_CHECKING:  # pragma: no cover
    from gui.components.model_view_widget import ModelViewWidget

class ContourDefinitionComponent:
    def set_contour_point_insert_strategy(self: "ModelViewWidget", strategy: str) -> None:
        """Задать стратегию вставки узлов контура: append | nearest_segment."""
        value = str(strategy or "").strip().lower()
        if value not in {"append", "nearest_segment"}:
            value = "append"
        self._contour_point_insert_strategy = value

    def start_contour_definition(self: "ModelViewWidget") -> None:
        """Включить режим построения прямоугольного контура по узлам сетки."""
        self._contour_point_insert_strategy = "append"
        self._contour_aux_hidden = False
        self._contour_drag_active = False
        self._contour_drag_point_index = None
        self._contour_drag_moved = False
        self._contour_ready = False
        try:
            self.contour_ready_changed.emit(False)
        except Exception as e:
            log_exception(__name__, "start_contour_definition", e)
        self._contour_points = []
        self._selected_cells = set()
        self._selection_anchor = None
        self._selection_start_cell = None
        self._update_contour_visualization()
        self._update_selection_visualization()
        # Сценарий взаимодействия
        mgr = getattr(self, "_interaction_manager", None)
        if mgr is not None:
            from gui.components.model_view._scenario_contour_edit import ContourEditScenario
            mgr.push(ContourEditScenario())

    def stop_contour_definition(self: "ModelViewWidget") -> None:
        """Выключить режим построения контура."""
        # Убрать сценарий взаимодействия
        mgr = getattr(self, "_interaction_manager", None)
        if mgr is not None:
            mgr.pop_by_name("contour_edit")
        self._restore_overlay_parent_visual()
        self._contour_drag_active = False
        self._contour_drag_point_index = None
        self._contour_drag_moved = False
        self._contour_point_insert_strategy = "append"
        self._contour_aux_hidden = False
        was_ready = bool(getattr(self, "_contour_ready", False))
        self._contour_ready = False
        if was_ready:
            try:
                self.contour_ready_changed.emit(False)
            except Exception as e:
                log_exception(__name__, "stop_contour_definition", e)
        self._contour_points = []
        self._clear_contour_actors()
        # Очистить размерные линии
        if getattr(self, "_dim_enabled", False):
            self.disable_dimension_lines()
        # Очистить состояние overlay-выбора зоны, если оно было активно
        self._cleanup_overlay_selection()

    def set_contour_zone_overlay_enabled(self: "ModelViewWidget", enabled: bool) -> None:
        """Включить/выключить режим наложения контура на существующие зоны."""
        self._contour_zone_overlay_enabled = bool(enabled)
        if not enabled:
            self._restore_overlay_parent_visual()
            self._contour_zone_mode = None
            self._contour_zone_id = None
            self._grid_plane_z_override = None
            self._clear_surface_grid()
            try:
                self._show_grid_actors()
            except Exception as e:
                log_exception(__name__, "set_contour_zone_overlay_enabled", e)

    def _clear_surface_grid(self: "ModelViewWidget") -> None:
        meshes = getattr(self, "_grid_surface_meshes", [])
        for mesh in list(meshes):
            try:
                if self._plotter:
                    self._plotter.remove_actor(mesh)
            except Exception as e:
                log_exception(__name__, "_clear_surface_grid", e)
        self._grid_surface_meshes = []
        self._grid_surface_nodes = []

    def _set_ground_mode(self: "ModelViewWidget") -> None:
        """Активировать разметку на базовой (напольной) сетке."""
        self._restore_overlay_parent_visual()
        self._contour_zone_mode = "ground"
        self._contour_zone_id = None
        self._grid_plane_z_override = None
        self._clear_surface_grid()
        try:
            self._show_grid_actors()
        except Exception as e:
            log_exception(__name__, "_set_ground_mode", e)

    def finalize_contour_selection(self: "ModelViewWidget") -> bool:
        """Зафиксировать объём по точечной разметке и отключить дальнейшее создание кликами."""
        polygon = self._extract_orthogonal_polygon()
        if polygon is None:
            return False
        if not self._validate_contour_closing_segment():
            return False
        self._update_selected_cells_from_contour()
        if not self._selected_cells:
            return False
        self._selected_height = 0
        self._update_selection_visualization()
        self._final_contour_points = list(polygon)
        self.stop_contour_definition()
        self._zone_selection_mode = False
        self._volume_locked_from_contour = True
        try:
            self._clear_surface_grid()
        except Exception as e:
            log_exception(__name__, "finalize_contour_selection", e)
        try:
            self._hide_grid_actors()
        except Exception as e:
            log_exception(__name__, "finalize_contour_selection", e)
        return True
