from __future__ import annotations

from pathlib import Path
from typing import Final

import axipy
from PySide2.QtCore import QSize
from PySide2.QtGui import QIcon
from PySide2.QtWidgets import QFileDialog
from .observer import SpatialFilterObserver
from .utils import SUPPORTED_TYPES_MESSAGE
from .worker import Worker

ICON_PATH: Final[Path] = Path(__file__).parent / "documentation" / "images"
ICON_NAME: Final[str] = "points_catalog.png"

ICON_SIZES: Final[tuple[int, ...]] = (16, 24, 32)


class SpatialFilter(axipy.Plugin):

    def __init__(self) -> None:
        self.title: str = self.tr("Обрезка по полигону")
        tooltip: str = self.tr("Обрезка по полигону (Пространственный фильтр)")

        self._observer = SpatialFilterObserver()

        self._button = axipy.ActionButton(
            title=self.title,
            tooltip=tooltip,
            on_click=self.on_click,
            enable_on=self._observer,
            icon=self._create_icon(),
        )

        position = axipy.Position(self.tr("Основные"), self.tr("Команды"))
        position.add(self._button)

    def _create_icon(self) -> QIcon:
        icon = QIcon()
        for size in ICON_SIZES:
            icon_path: str = str(ICON_PATH / f"{size}px" / ICON_NAME)
            icon.addFile(icon_path, QSize(size, size))
        return icon

    def on_click(self) -> None:
        dt = axipy.DialogTask(SpatialFilterObserver.check_if_only_supported_types_selected)
        if dt.run_and_get():
            folder: str = QFileDialog.getExistingDirectory(
                axipy.view_manager.global_parent,
                self.tr("Выбор папки для сохранения отредактированных таблиц"),
                str(axipy.CurrentSettings.LastSavePath),
            )
            if not folder:
                return None

            folder: Path = Path(folder)
            axipy.CurrentSettings.LastSavePath = folder

            Worker(self, folder).run_and_get()
        else:
            axipy.show_message(
                title=self.tr("Предупреждение"),
                text=self.tr(
                    "Неподдерживаемые типы геометрии в выборке.\n"
                    f"Поддерживаемые типы: {SUPPORTED_TYPES_MESSAGE}."
                ),
                icon=axipy.DlgIcon.WARNING,
            )

    def unload(self) -> None:
        self._observer.unload()
        self._button.remove()
