import asyncio
import importlib
from signal import Signals
from types import ModuleType
from typing import Callable


def get_application(application_name: str) -> Callable | ModuleType:
    """
    Load a callable from a `module.submodule:Object.callable` string.

    From https://github.com/sivulich/mqttasgi/blob/master/mqttasgi/utils.py
    """
    module_path, object_path = application_name.split(":", 1)
    application = importlib.import_module(module_path)
    for bit in object_path.split("."):
        application = getattr(application, bit)

    if hasattr(application, "as_asgi"):
        return application.as_asgi()

    return application


def terminate(event: asyncio.Event, signal: Signals) -> None:  # pragma: no cover
    """
    Close the event loop.
    """
    event.set()
    asyncio.get_running_loop().remove_signal_handler(signal)
