from typing import Any, Optional, cast

import axipy
import shiboken2
from PySide2.QtGui import QIcon

from .export_to_db_dialog import ExportToDbDialog


class ExportToDatabase(axipy.Plugin):

    def __init__(self) -> None:
        self.title = self.tr("Экспорт в БД")
        self.__dialog: Optional[ExportToDbDialog] = None
        self.__button: Optional[axipy.ActionButton] = axipy.ActionButton(
            title=self.title,
            on_click=self.on_click,
            icon=QIcon.fromTheme("export_to_db"),
        )
        position = axipy.Position(axipy.tr("Основные"), axipy.tr("Команды"))
        position.add(self.__button)

    def __shiboken2_is_valid(self, obj: Any) -> bool:
        return shiboken2.isValid(obj)

    def __dialog_is_valid(self) -> bool:
        return self.__dialog is not None and self.__shiboken2_is_valid(self.__dialog)

    @property
    def dialog(self) -> ExportToDbDialog:
        if not self.__dialog_is_valid():
            self.__dialog = ExportToDbDialog(self)
        return cast(ExportToDbDialog, self.__dialog)

    def unload(self) -> None:
        if self.__button is not None:
            self.__button.remove()
            self.__button = None

        if self.__dialog_is_valid():
            cast(ExportToDbDialog, self.__dialog).deleteLater()
            self.__dialog = None

    def on_click(self) -> None:
        self.dialog.open()
