from __future__ import annotations

from pathlib import Path
from typing import Final

import axipy
from PySide2.QtCore import QSize, Qt
from PySide2.QtGui import QIcon
from PySide2.QtWidgets import QMessageBox
from axipy import ActionButton, Position, Plugin, view_manager, data_manager
from .register_vector_dialog import RegisterVectorDialog
from .utils import filter_one_input_table

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

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


class RegisterVector(Plugin):

    def __init__(self) -> None:
        self._button = ActionButton(
            title=self.tr("Привязка\nвектора"),
            on_click=self.on_click,
            icon=self._create_icon(),
            enable_on=axipy.ObserverManager.HasTables,
        )
        position = 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 unload(self) -> None:
        self._button.remove()

    @staticmethod
    def can_open_dialog() -> bool:
        if (
                len(view_manager.mapviews) > 0 and
                any(filter_one_input_table(table) for table in data_manager.tables)
        ):
            return True
        else:
            return False

    def on_click(self) -> None:
        if not self.can_open_dialog():
            mbox = QMessageBox(
                QMessageBox.Critical,
                "Ошибка запуска модуля",
                "Для запуска модуля необходимо открыть: \n"
                "1) Таблицу Tab (*.tab) с геометрией;\n"
                "2) Карту.",
                parent=view_manager.global_parent,
            )
            mbox.open()
            return None

        dialog = RegisterVectorDialog(self, parent=view_manager.global_parent)
        dialog.setWindowIcon(self._button.action.icon())
        dialog.setAttribute(Qt.WA_DeleteOnClose, True)
        dialog.open()
