from typing import List

import axipy
from PySide2.QtSql import QSqlQuery


# noinspection PyMethodMayBeStatic
class DialogTaskCustom(axipy.DialogTask):

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(self.create_selection, *args, **kwargs)

    def ensure_sql_init_for_bg_thread(self) -> None:
        def ensure_sql_init_for_bg_thread() -> None:
            query = QSqlQuery(axipy.gui_instance.database())
            query.exec_("Select 'Init SQL Engine'")

        axipy.run_in_gui(ensure_sql_init_for_bg_thread)

    def create_selection(self, table: axipy.Table, is_show_table_view: bool) -> int:
        self.infinite_progress = True
        if is_show_table_view:
            self.ensure_sql_init_for_bg_thread()
            query = axipy.data_manager.query(
                f"select * from {table.name} where obj is NULL",
                dialect=axipy.TypeSqlDialect.sqlite,
            )
            count = query.count()
            if count > 0:
                ids: List[int] = [f.id for f in query.items()]
                count = len(ids)
                if count > 0:
                    axipy.selection_manager.clear()
                    axipy.selection_manager.add(query, ids)
                axipy.run_in_gui(axipy.view_manager.create_tableview, query)
            else:
                query.close()

        else:
            ids: List[int] = [f.id for f in table.items() if f.geometry is None]
            count = len(ids)
            if count > 0:
                axipy.selection_manager.clear()
                axipy.selection_manager.add(table, ids)
        return count

    def run_and_get(self, table: axipy.Table, is_show_table_view: bool) -> int:
        return super().run_and_get(table, is_show_table_view)
