# 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 QPolaris.modules.processing_provider.polaris_base_algorithm import PolarisProcessingAlgorithm
from polaris.utils.database.db_utils import commit_and_close
from polaris.utils.database.standard_database import StandardDatabase, DatabaseType

from QPolaris import get_polaris_menu_instance


def add_triggers_action():
    proj = get_polaris_menu_instance()
    if not proj.open_mode:
        proj.show_message_no_supply()
    else:
        from polaris.network.create.triggers import create_network_triggers, create_triggers

        with commit_and_close(proj.supply_path, spatial=True) as conn:
            create_network_triggers(conn)
        if proj.open_mode == "project" and proj.freight_path.exists():
            with commit_and_close(proj.freight_path, spatial=True) as conn:
                create_triggers(StandardDatabase.for_type(DatabaseType.Freight), conn)
        proj.show_error_message(message="Added triggers back to the model", level=2)


class AddTriggers(PolarisProcessingAlgorithm):
    def __init__(self):
        super().__init__(
            add_triggers_action,
            "add_triggers",
            "Add Triggers",
            "Model Maintenance",
            "model_maintenance",
            "Add triggers to the Supply and freight databases",
            ["maintenance", "editing", "triggers", "add"],
        )

    def createInstance(self):
        return AddTriggers()
