#!/usr/bin/python
"""
Send a result to RabbitMQ.
"""

# Note that this imports the local copy, not what's installed on the
# system.
import pika
import sys

import pscheduler


MAX_SCHEMA = 1


def archive(json):

    schema = json["data"].get("schema", 1)
    if schema > MAX_SCHEMA:
        return {
            "succeeded": False,
            "error": "Unsupported schema version %d; max is %d" % (
                schema, MAX_SCHEMA)
        }

    data = json["data"]

    try:

        connection = pika.BlockingConnection(
            pika.URLParameters(data["_url"])
        )

        connection.channel().basic_publish(
            exchange=data.get("exchange", ""),
            routing_key=data.get("routing-key", ""),
            body=pscheduler.json_dump(json["result"])
        )

        connection.close()

        result = {'succeeded': True}

    except Exception as ex:

        try:
            if ex.__module__ == "pika.exceptions":
                error = "Pika error: %s" % (ex.__class__.__name__)
            else:
                error = str(ex)
        except AttributeError:
            error = str(ex)

        result = {
            "succeeded": False,
            "error": error
        }

        if "retry-policy" in data:
            policy = pscheduler.RetryPolicy(data["retry-policy"], iso8601=True)
            retry_time = policy.retry(json["attempts"])
            if retry_time is not None:
                result["retry"] = retry_time

    return result



PARSER = pscheduler.RFC7464Parser(sys.stdin)
EMITTER = pscheduler.RFC7464Emitter(sys.stdout)

for parsed in PARSER:
    EMITTER(archive(parsed))

pscheduler.succeed()
