# 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(__file__), "forms/geo_consistency.ui"))


class GlobalGeoconsistency(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.worker_thread = self._p.geo_consistency
        self.__mt = ""

        self.but_process.clicked.connect(self.process_consistency)
        self.but_clear.clicked.connect(self.clear_all_actions)
        self.but_select_all.clicked.connect(self.select_all_actions)
        self.progressBar.setVisible(False)
        self.progressBar.setEnabled(False)
        self.setFixedHeight(232)
        self.__chk_boxes = {
            self.chk_active_links: self.worker_thread.update_active_network_association,
            self.chk_area_type_association: self.worker_thread.update_area_type_association,
            self.chk_county_association: self.worker_thread.update_county_association,
            self.chk_links: self.worker_thread.update_link_association,
            self.chk_location_association: self.worker_thread.update_location_association,
            self.chk_popsyn_association: self.worker_thread.update_popsyn_region_association,
            self.chk_zone_association: self.worker_thread.update_zone_association,
        }
        self.items = [self.but_process, self.but_clear, self.but_select_all, self.progressBar, self.options_box]

    def clear_all_actions(self):
        for item in self.__chk_boxes.keys():
            item.setChecked(False)

    def select_all_actions(self):
        for item in self.__chk_boxes.keys():
            item.setChecked(True)

    def process_consistency(self):
        for item in self.items:
            item.setVisible(not item.isVisible())
            item.setEnabled(not item.isEnabled())
        self.setFixedHeight(176)

        self.progressBar.setVisible(True)

        tot = sum(1 for item in self.__chk_boxes.keys() if item.isChecked())
        if tot == 0:
            return
        self.progressBar.setRange(0, tot)

        for item, func in self.__chk_boxes.items():
            if item.isChecked():
                func()
                self.progressBar.setValue(self.progressBar.value() + 1)
