# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
import gc
import importlib.util as iutil
import sys
from os.path import dirname, join

import qgis
from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QDialog

from ..common_tools import ReportDialog

sys.modules["qgsfieldcombobox"] = qgis.gui
sys.modules["qgsmaplayercombobox"] = qgis.gui
FORM_CLASS, _ = uic.loadUiType(join(dirname(__file__), "forms/checker.ui"))


class CheckerDialog(QDialog, FORM_CLASS):
    def __init__(self, _PQgis):
        QDialog.__init__(self)
        self.iface = _PQgis.iface
        self.setupUi(self)
        self._testing = False
        self._PQgis = _PQgis
        self._p = _PQgis.polaris_project.network

        self.but_process.clicked.connect(self.perform_tests)
        self.but_clear.clicked.connect(self.clear_all)
        self.but_select_all.clicked.connect(self.select_all_tests)

        self.tests_dictionary = {
            self.chk_critical: "critical",
            self.chk_consistency_tests: "consistency_tests",
            self.chk_connections_table: "connections_table",
        }

        self.worker_thread = self._p.checker

        self.progressBar.setVisible(False)
        self.lbl_progress.setVisible(False)
        self.resize(232, 340)
        self.__curr_run = ""
        self.__curr_errors = 0
        self.__tot_ran = 0

    def clear_all(self):
        for item in self.tests_dictionary.keys():
            item.setChecked(False)

    def select_all_tests(self):
        for item in self.tests_dictionary.keys():
            item.setChecked(True)

    def perform_tests(self):
        self.resize(232, 420)
        self.but_process.setEnabled(False)
        self.but_clear.setEnabled(False)
        self.but_select_all.setEnabled(False)
        for item in self.tests_dictionary.keys():
            item.setEnabled(False)

        self.progressBar.setVisible(True)
        self.lbl_progress.setVisible(True)

        tests = [method for item, method in self.tests_dictionary.items() if item.isChecked()]
        self.worker_thread.set_test_list(tests)

        self.worker_thread.checking.connect(self.signal_handler)
        self.worker_thread.start()
        self.exec_()

    def signal_handler(self, val):
        if val[0] == "finished_checking_procedure":
            self.after_run()
            return

        bar = self.progressBar
        lbl = self.lbl_progress2 if val[1] == "master" else self.lbl_progress

        if val[0] == "start":
            lbl.setText(val[3])
            bar.setRange(0, val[2])
        elif val[0] == "update":
            bar.setValue(val[2])

    def after_run(self):
        self.close()
        if not self._testing:
            if self.worker_thread.errors:
                dlg2 = ReportDialog(self.iface, self.worker_thread.errors)
                dlg2.show()
                dlg2.exec_()
            else:
                self.iface.messageBar().pushMessage("Awesome. No issues found", level=3, duration=10)
        del self.worker_thread
        gc.collect()
