from typing import TYPE_CHECKING, Optional, List

import PySide2.QtWidgets
import axipy
from axipy import Notifications
from .observer import get_spatial_tables
from .ui.ui_dialog import Ui_Dialog
from .worker import DialogTaskCustom

if TYPE_CHECKING:
    from .__init__ import FindFeaturesNoGeom


class Dialog(PySide2.QtWidgets.QDialog, Ui_Dialog):

    def __init__(self, plugin: 'FindFeaturesNoGeom', *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.setupUi(self)
        self.plugin: 'FindFeaturesNoGeom' = plugin

        table_names: List[str] = list(t.name for t in get_spatial_tables())
        # set selection table as first
        selection_table: Optional[axipy.SelectionTable] = axipy.data_manager.selection
        selection_table_exists: bool = selection_table is not None
        if selection_table_exists:
            selection_table_name: str = selection_table.name
            if selection_table_name in table_names:
                table_names.remove(selection_table_name)
                table_names.insert(0, selection_table_name)

        self.cb_choose_table.addItems(table_names)

        force_check_show_table_view: bool = True
        if not selection_table_exists:
            # Choose current table from active TableView
            active_view = axipy.view_manager.active
            if isinstance(active_view, axipy.TableView):
                name = active_view.data_object.name
                if name in table_names:
                    index = table_names.index(name)
                    self.cb_choose_table.setCurrentIndex(index)
                    force_check_show_table_view = False

        self.settings_key_show_table_view = "chk_show_table_view"
        value = self.plugin.settings.value(self.settings_key_show_table_view, False, bool)
        if force_check_show_table_view and value is False:
            value = True
        self.chk_show_table_view.setChecked(value)

    def done(self, return_code: int) -> None:
        if return_code == self.Accepted:
            is_checked = self.chk_show_table_view.isChecked()
            self.plugin.settings.setValue(self.settings_key_show_table_view, is_checked)
            self.create_selection(self.cb_choose_table.currentText(), is_checked)
        super().done(return_code)

    def create_selection(self, table_name: str, is_show_table_view: bool) -> None:
        table = axipy.data_manager.find(table_name)
        if not isinstance(table, axipy.Table):
            axipy.Notifications.push(
                self.plugin.title,
                self.plugin.tr(f"Не удалось найти таблицу с именем '{table_name}'."),
                axipy.Notifications.Critical,
            )
            return None

        dt = DialogTaskCustom(title="Поиск записей без геометрии")
        count = dt.run_and_get(table, is_show_table_view)

        if count > 0:
            axipy.Notifications.push(
                self.plugin.title,
                self.plugin.tr(f"В таблице '{table_name}'\nнайдено {count} записей без геометрии."),
                Notifications.Warning,
            )
        else:
            axipy.Notifications.push(
                self.plugin.title,
                self.plugin.tr(f"В таблице '{table_name}'\nнет записей без геометрии."),
                Notifications.Success,
            )
