# Copyright (c) 2025, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copyright (c) 2025, 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(__file__), "forms/ui_library_tool.ui"))


class LinkSizeLimiterDialog(QDialog, FORM_CLASS):
    def __init__(self, _PQgis):
        QDialog.__init__(self)
        self.iface = _PQgis.iface
        self.setupUi(self)
        self.finished = False
        self._PQgis = _PQgis
        self._p = _PQgis.network
        self.worker_thread = self._p.tools

        self.but_process.clicked.connect(self.break_links)
        self.but_process.setText("Break links above threshold")
        self.do_multiple.setVisible(False)
        self.progress_box.setVisible(False)
        self.setFixedHeight(153)

    def break_links(self):
        self.progress_box.setVisible(True)
        self.parameter_box.setVisible(False)
        self.setFixedHeight(110)

        max_link = self.spinBox_lgth.value()
        self.worker_thread._set_work_to_do(["break_links", max_link])
        self.worker_thread.tooling.connect(self.signal_handler)
        self.worker_thread.doWork()

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

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

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