#!/usr/bin/env python3
import asyncio
import os
import signal
from concurrent.futures import ThreadPoolExecutor

from setproctitle import setproctitle

from ngcp_task_agent import app_config
from ngcp_task_agent.app import App

app = App()


async def shutdown() -> None:
    """Gracefully shuts down the wrapper.

    Stops the App

    Args:
        None

    Returns
        None

    """
    await app.stop()

    # shutdown all remaining pending asyncio tasks,
    # if there are any
    for task in asyncio.tasks.all_tasks():
        try:
            task.cancel()
        except asyncio.CancelledError:
            pass


async def main() -> None:
    """Async entry point function.

    Starts the App

    Args:
        None

    Returns
        None

    """
    await app.run()


if __name__ == '__main__':
    setproctitle(app_config.app_name)
    loop = asyncio.new_event_loop()
    executor = ThreadPoolExecutor()
    loop.set_default_executor(executor)
    for signame in ('SIGINT', 'SIGTERM', 'SIGHUP'):
        loop.add_signal_handler(getattr(signal, signame),
                                lambda: asyncio.ensure_future(shutdown()))
    try:
        loop.run_until_complete(main())
    except asyncio.exceptions.CancelledError:
        pass
    finally:
        loop.close()
