#!/usr/bin/env python3

import aiopg.sa
import asyncio
import logging
import ywsd.engine
import ywsd.objects
import ywsd.settings

import yate.asyncio

logger = logging.getLogger("fieldpoc.ywsd")

class Ywsd:
    def __init__(self, fp):
        self.fp = fp

        self.event_loop = asyncio.SelectorEventLoop()

    def settings(self):
        class Settings(ywsd.settings.Settings):
            def __init__(self, config):
                self.config = config

        return Settings({
            "RINGBACK_TOP_DIRECTORY": "/opt/sounds",
            "DB_CONFIG": {
                "host": self.fp.config.database.hostname,
                "user": self.fp.config.database.username,
                "password": self.fp.config.database.password,
                "database": self.fp.config.database.database,
            },
            "STAGE2_DB_CONFIG":{
                "host": self.fp.config.database.hostname,
                "user": self.fp.config.database.username,
                "password": self.fp.config.database.password,
                "database": self.fp.config.database.database,
             },
            "LOCAL_YATE_ID": 1,
            "INTERNAL_YATE_LISTENER": "voip",
            "CACHE_IMPLEMENTATION": "ywsd.routing_cache.PythonDictRoutingCache",
            "YATE_CONNECTION":{
                "host": self.fp.config.yate.host,
                "port": self.fp.config.yate.port,
            },
        })

    def init(self):
        async def amain(settings):
            async with aiopg.sa.create_engine(**settings.DB_CONFIG) as engine:
                async with engine.acquire() as conn:
                    await ywsd.objects.regenerate_database_objects(conn)

        asyncio.run(amain(self.settings()))


    def run(self):
        # Mokey patch python-yate so I don't have to fork it yet
        async def setup_for_tcp(self, host, port):
            self.reader, self.writer = await asyncio.open_connection(host, port)
            self.send_connect()
        yate.asyncio.YateAsync.setup_for_tcp = setup_for_tcp

        # Mokey patch ywsd so I don't have to fork it yet
        asyncio.set_event_loop(self.event_loop)
        def add_signal_handler(*args, **kwargs):
            raise NotImplementedError("Disable signal handling so we can run ywsd in a thread")
        asyncio.get_event_loop().add_signal_handler = add_signal_handler

        logger.info("starting ywsd")
        self.app = ywsd.engine.YateRoutingEngine(settings=self.settings(), web_only=False, **self.settings().YATE_CONNECTION)
        self.app.event_loop = self.event_loop
        self.app.run()

        logger.info("stopped ywsd")