# 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
import logging
from os.path import dirname, join

from polaris.runs.results.h5_results import H5_Results
from qgis.PyQt import QtWidgets, uic

from ..common_tools.path_drawer import PathDrawer

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

logger = logging.getLogger("polaris")


class PathResultH5(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, qgis_project) -> None:
        QtWidgets.QDialog.__init__(self)
        self.iface = qgis_project.iface
        self.qgis_project = qgis_project
        self.setupUi(self)
        self.field_types = {}
        self.link_layer = self.qgis_project.layers["link"][0]
        self.path_drawer = PathDrawer({"Links": ["link", self.link_layer]})

        self.path = []
        self.h5 = H5_Results(self.qgis_project.result_h5_path)
        self.do_path.clicked.connect(self.build_path)
        self.valid_paths = self.h5.get_path_links().path_id.unique()
        self.cob_paths.addItems([str(s) for s in self.valid_paths])

        if len(self.valid_paths) == 0:
            self.do_path.setEnabled(False)
            self.do_path.setText("No paths available")

    def build_path(self):
        path_id = int(self.cob_paths.currentText())

        self.path = self.h5.get_path_links(int(path_id)).link_id.tolist()

        if self.rdo_selection.isChecked():
            self.path_drawer.create_path_with_selection(self.path)
        else:
            _ = self.path_drawer.create_traffic_path_with_scratch_layer(path=self.path, layer_name=f"Path ID-{path_id}")

    def exit_procedure(self):
        self.close()
