#!/usr/bin/env python3
"""
Job handler server.

This applications consists in one AMQP client retrieving jobs from a queue and
pushing back results.
"""
from zope.component import getUtility

from storm.twisted.transact import Transactor

from twisted.application.service import Application
from twisted.internet import reactor

from canonical.amqp.job.handler import JobHandler
from canonical.amqp.job.registry import JobRegistry
from canonical.amqp.message.interfaces import IPublisher

from canonical.landscape.setup import setup_broker, load_config
from canonical.landscape.environment import get_modules
from canonical.landscape.scripts.job_handler import run
from canonical.landscape.model.configuration import set_proxy_configuration


if __name__ == "__main__":
    run()


config = load_config("job-handler")

application = Application("job-handler")
job_handler_config = config.get("job-handler")

threadpool = reactor.getThreadPool()
transactor = Transactor(threadpool)

modules = get_modules(["model/*/jobs", "model/*/jobs.py"])
registry = JobRegistry(transactor=transactor, echo=True)
registry.scan(modules)
accumulator_reconnection_delay = int(
    job_handler_config.get("accumulator-reconnection-delay", 60))
default_accumulator_delay = int(
    job_handler_config.get("default-accumulator-delay", 60))
publisher = getUtility(IPublisher)
handler = JobHandler(registry, "landscape", reactor,
                     accumulator_reconnection_delay, default_accumulator_delay,
                     publisher)
reactor.addSystemEventTrigger("before", "shutdown",
                              handler.fire_pending_accumulated)

setup_broker(config, handler.connected, handler.disconnected, application)

# This transaction is run in the main thread, which is bad. Eventually
# we want to move startup-related queries in some well defined spot, which
# is guaranted to be run in the threadpool and be committed.
import transaction
set_proxy_configuration()
transaction.commit()
