#!/usr/bin/env python3
import argparse
import asyncio
import json
import logging
import sys

import ebosia.async

LOGGER = logging.getLogger('emitter')

def _on_event(event):
    LOGGER.info("Event: %s", event)

def main():
    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)

    parser = argparse.ArgumentParser()

    parser.add_argument('-t', '--topic', default='dev-eventbus', help='The topic of the event to publish')
    parser.add_argument('-c', '--content', default='{"hello":"world"}', help="a JSON string that will be sent as the content of the event")
    parser.add_argument('-u', '--connection-url', default='amqp://guest:guest@localhost', help='The connection string for RabbitMQ')
    parser.add_argument('-r', '--repeat', default=None, type=int, help='A number of times to repeat the message')
    args = parser.parse_args()

    try:
        content = json.loads(args.content)
    except ValueError as e:
        LOGGER.error("Cannot parse %s as JSON: %s", args.content, e)
        return -1

    loop = asyncio.get_event_loop()
    coro = pushit(args.connection_url, args.topic, content, args.repeat)
    loop.run_until_complete(coro)

@asyncio.coroutine
def pushit(connection_url, topic, content, repeat):
    yield from ebosia.async.connect(connection_url)
    repeat = repeat or 1
    for _ in range(repeat):
        yield from ebosia.async.publish(topic, content)
        yield from asyncio.sleep(3)

if __name__ == "__main__":
    sys.exit(main())
