# 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 qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QDialog

from polaris.network.tools.create_connections import CreateConnections

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


class IntersectionRebuilderDialog(QDialog, FORM_CLASS):
    def __init__(self, _PQgis):
        QDialog.__init__(self)
        self.iface = _PQgis.iface
        self.finished = False
        self.setupUi(self)

        self._PQgis = _PQgis

        self.but_rebuild.clicked.connect(self.rebuild_intersections)
        self.worker_thread: CreateConnections
        self.progress_box.setEnabled(False)
        self.progress_box.setVisible(False)
        self.setFixedHeight(178)

    def rebuild_intersections(self):
        for item in [self.but_rebuild, self.groupBoxSignal, self.groupSign, self.progress_box]:
            item.setVisible(not item.isVisible())
            item.setEnabled(not item.isEnabled())
        self.setFixedHeight(110)
        signs = None if self.rdoExistingStopSign.isChecked() else []
        signals = "geometric" if self.rdoGeometrySignal.isChecked() else "osm" if self.rdoOSM.isChecked() else None
        self.worker_thread = CreateConnections(
            self._PQgis.network.tables, self._PQgis.supply_path, signals, signs, False
        )

        self.worker_thread.connecting.connect(self.signal_handler)
        self.worker_thread.doWork()
        self.worker_thread.finish()

    def signal_handler(self, val):
        if len(val) == 1:
            if val[0] == "finished_rebuilding_procedure":
                self.finished = True
                self.close()
            return

        bar = None if val[1] == "master" else self.progressBar

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

    def closeEvent(self, event):
        event.accept()
