# 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 qgis.core import QgsProject

from ..common_tools import QGISConsistencyEnforcer
from ..common_tools.point_tool import PointTool


class NetEditor:
    def __init__(self, qgis_proj):
        self.iface = qgis_proj.iface
        self._PQgis = qgis_proj
        self._p = qgis_proj.network
        self.data_tables = self._p.tables

        self.required_layers = ["Node", "Link"]

        # layers already loaded
        layer_ids = [layer.id() for layer in QgsProject.instance().mapLayers().values()]

        for lyr in self.required_layers:
            if lyr.lower() not in self._PQgis.layers:
                print("Layer was not found, which is weird")
                self._PQgis.create_layer_by_name(lyr)

        self.clickTool = PointTool(qgis_proj.iface.mapCanvas())
        self.canvas = self.iface.mapCanvas()

        for lyr in self.required_layers:
            layer_id = self._PQgis.layers[lyr.lower()][1]
            if layer_id not in layer_ids:
                self._PQgis.load_layer_by_name(lyr)

    def editing(self):
        self.data_tables.refresh_cache("Link")
        self.data_tables.refresh_cache("Node")
        cons = QGISConsistencyEnforcer(self._PQgis)
        cons.execute()
