# 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
from os.path import dirname, join
from polaris.network.consistency.consistency import Consistency
from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QDialog

from .is_test import running_on_ci

FORM_CLASS, _ = uic.loadUiType(join(dirname(__file__), "forms/progress.ui"))


class QGISConsistencyEnforcer(QDialog, FORM_CLASS):
    def __init__(self, _PQgis):
        QDialog.__init__(self)
        self.iface = _PQgis.iface
        self.setupUi(self)
        self._PQgis = _PQgis

        self.worker_thread = Consistency(_PQgis.network.path_to_file)

    def execute(self):
        self.worker_thread.consistency.connect(self.signal_handler)
        self.worker_thread.run()
        if not running_on_ci():
            self.exec_()

    def signal_handler(self, val):
        if val[0] == "start":
            self.setWindowTitle("Enforcing consistency")
            self.progressBar.setMaximum(val[2])
            self.lbl_progress.setText(val[3])
        elif val[0] == "update":
            self.progressBar.setValue(val[2])
        elif val[0] == "finished_consistency_procedure":
            self.close()
