# 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

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


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

        self._PQgis = _PQgis
        self._p = _PQgis.network
        self.setWindowTitle("Rebuilding Active networks")
        self.but_execute.clicked.connect(self.execute)
        self.but_execute.setText("Rebuild Walk and Bike networks")
        self.grp_progress.setVisible(False)
        self.setFixedHeight(52)

    def execute(self):
        self.grp_progress.setVisible(True)
        self.but_execute.setVisible(False)
        self.setFixedHeight(137)

        walk = self._p.active
        walk.activenet.connect(self.signal_handler)
        walk.doWork()

    def signal_handler(self, val):
        if len(val) == 1:
            self.close()
            return

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

        if val[0] == "start":
            lbl.setText(val[3])
            bar.setRange(0, val[2])
            bar.setValue(0)
        elif val[0] == "update":
            bar.setValue(val[2])
            if val[1] != "master" and bar.maximum() == val[2]:
                self.progressBar.setValue(self.progressBar.value() + 1)
