# 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
import qgis
from polaris import Polaris
from polaris.network.network import Network
from qgis.core import QgsProject
from polaris.utils.database.db_utils import has_table, count_table
from .run_consist import run_consistency


def close_project(qgis_project):
    if not qgis_project.open_mode:
        qgis_project.show_message_no_supply()
        return

    qgis.gui.QgsMapCanvas().freeze(True)
    remove = [lyr[1] for lyr in qgis_project.layers.values()]
    qgis_project.layers.clear()
    QgsProject.instance().removeMapLayers(remove)
    qgis.gui.QgsMapCanvas().freeze(False)
    qgis_project.iface.mapCanvas().refresh()

    with qgis_project.supply_conn as conn:
        if has_table(conn, "Geo_Consistency_Controller"):
            if count_table(conn, "Geo_Consistency_Controller") > 0:
                qgis_project.show_message_geoconsistency_issues()
        else:
            qgis_project.show_error_message(
                "Your project needs to be upgraded. It does not have the Geo_Consistency_Controller table."
            )

    qgis_project.cob_iter.clear()
    qgis_project._network = Network()
    qgis_project.polaris_project = Polaris()
    qgis_project.alternative_project = Polaris()
    qgis_project.open_mode = None

    qgis_project.geo_layers_table.setRowCount(0)
    qgis_project.geo_layers_table.setColumnCount(0)
