#!/usr/bin/env python3
#

import sys
import signal
import pika
import time
import json
import uuid
import random

workertype = None

def signal_handler(signum, frame):
    sig = dict((k, v) for v, k in reversed(sorted(signal.__dict__.items())) if v.startswith('SIG') and not v.startswith('SIG_'))
    print('\n*** '+str(sig[signum])+' received. Graceful shutdown.')
    sys.exit(0)


def on_message(channel, method_frame, header_frame, body):
    print('*** on_message(): '+workertype+'-'+str(method_frame.delivery_tag))
    print(body)
    ret = dict()
    startmillis = int(round(time.time() * 1000))

    ret['requestId'] = str(uuid.uuid1())

    # pseudo-work
    if workertype == 'document':
        time.sleep(random.randint(3,5))
    if workertype == 'quiz':
        time.sleep(random.randint(1,2))
    if workertype == 'video':
        time.sleep(random.randint(8,11))

    ret['processingTime'] = str(int(round(time.time() * 1000))-startmillis)
    channel.basic_ack(delivery_tag=method_frame.delivery_tag)
    channel.basic_publish('dst.workers', 'requests.'+workertype, json.dumps(ret), pika.BasicProperties())


def mainloop():
    connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.99.99',credentials=pika.PlainCredentials('dst', 'dst')))
    channel = connection.channel()
    channel.queue_declare(queue='dst.'+workertype, durable=True, exclusive=False, auto_delete=False)
    channel.basic_qos(prefetch_count=1)
    channel.basic_consume(on_message, queue='dst.'+workertype)

    print('*** Starting consuming.')
    channel.start_consuming()


if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('Takes exactly one parameter: WORKERTYPE')
        sys.exit(0)

    workertype = sys.argv[1]
    print('*** Starting worker of type: '+workertype)
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)
    mainloop()
