# 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 QgsDataSourceUri, QgsVectorLayer, QgsProject

from .style_loader import load_style_by_name


def intersec_ctrl(qgis_project):
    # First we create the layer for intersection
    sql = """SELECT l.*, s.sign ab_sign, s2.sign ba_sign, sig.type ab_signal, sig2.type ba_signal FROM "link" l
             LEFT OUTER JOIN sign AS s ON l.node_b=s.nodes AND l.link=s.link
             LEFT OUTER JOIN sign AS s2 ON l.node_a=s2.nodes AND l.link=s2.link
             LEFT OUTER JOIN signal AS sig ON l.node_b=sig.nodes
             LEFT OUTER JOIN signal AS sig2 ON l.node_a=sig2.nodes"""

    file_pth = qgis_project.supply_path
    uri = QgsDataSourceUri()
    uri.setDatabase(file_pth)

    uri.setDataSource("", f"({sql})", "geo", "", "link")
    layer = QgsVectorLayer(
        uri.uri(),
        "links_intersection_control",
        "spatialite",
    )

    load_style_by_name(layer, "link_intersection_control.qml")
    QgsProject.instance().addMapLayer(layer)

    load_style_by_name(qgis_project.layers["node"][0], "intersection_control_nodes.qml")
    QgsProject.instance().addMapLayer(qgis_project.layers["node"][0])
    qgis_project.iface.mapCanvas().refresh()
