from __future__ import annotations

from pathlib import Path
from typing import Final, TYPE_CHECKING, Optional

import axipy
from PySide2.QtCore import QSize
from PySide2.QtGui import QIcon
from .worker import Worker

if TYPE_CHECKING:
    from .connection_dialog import ConnectionParams

ICON_PATH: Final[Path] = Path(__file__).parent / "documentation" / "images"
ICON_NAME: Final[str] = "open_postgre_raster.png"
ICON_SIZES: Final[tuple[int, ...]] = (16, 24, 32)


class OpenPostgreRasterPlugin(axipy.Plugin):

    def __init__(self) -> None:
        self.title: str = self.tr("Открыть растр из PostgreSQL")
        tooltip: str = self.tr("Открыть растр из PostgreSQL.")

        self._button = axipy.ActionButton(
            title=self.title,
            tooltip=tooltip,
            on_click=self.on_click,
            icon=self._create_icon()
        )
        self.worker_: Worker | None = None
        self.__connection_params: Optional['ConnectionParams'] = None

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

    def save_connection_params(self, params: 'ConnectionParams') -> None:
        self.__connection_params = params

    def restore_connection_params(self) -> Optional['ConnectionParams']:
        return self.__connection_params

    def _create_icon_from_name(self, name: str) -> QIcon:
        result = axipy.action_manager.icons.get(name, None)
        return result if result else QIcon()

    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:
        self.worker_ = Worker(self)
        self.worker_.run_and_get()

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