#!/usr/bin/python
"""
    mahali_pubsub_client.py

    $Id: mahali_pubsub_client.py 476 2015-08-13 21:20:35Z flind $

    This software implements a generic client for redis pubsub queues as used in Mahali where
    serialized json objects are used for command, control, and status. This client does not
    interpret the objects but provides a formatted printout of their content. Command line
    options allow for arbitrary queue filters, message type filters, and output of a finite
    or unbounded number of messages.

"""

import time
import sys
import os
import optparse
import numpy
import json
import redis

import mahali_common

DEBUG = False


def parse_command_line():
    parser = optparse.OptionParser()
    parser.add_option("-v", "--verbose",action="store_true", dest="verbose", default=False,help="Print message details.")
    parser.add_option("-d", "--debug",action="store_true", dest="debug", default=False,help="Print debug messages to stdout.")
    parser.add_option("-q", "--queuefilter",dest="QFILTER",help="Use filter QFILTER to select mahali pubsub queue.")
    parser.add_option("-n", "--number",dest="NMSG",help="Accept NMSG messages and then exit. ")

    (options, args) = parser.parse_args()

    return (options, args)

if __name__ == '__main__':

    msg_cnt = 0
    max_msg_cnt = -1

    # parse command line options
    options, args = parse_command_line()

    if options.NMSG:
        max_msg_cnt = options.NMSG


    # activate service with debug to console
    if options.debug:
        DEBUG = options.debug

    # create redis interface
    redis_db = redis.StrictRedis(host='localhost', port=6379, db=0)

    pubsub = redis_db.pubsub()


    if options.QFILTER:
        channel = options.QFILTER
    else:
        channel = 'mahali-*'

    pubsub.psubscribe(channel)

    try:

        for msg in pubsub.listen():

            #msg = pubsub.get_message()

            if msg:
                print msg
            else:
                continue

            # if we
            if max_msg_cnt != -1:
                if msg_cnt > max_msg_cnt:
                    break

                msg_cnt = msg_cnt + 1

            #time.sleep(0.1)

    except KeyboardInterrupt:
        print("exiting mahali pubsub client on keyboard interrupt")

    except Exception as eobj:
        exp_str = str(ExceptionString(eobj))
        emsg = "exception: %s. Problem with mahali pubsub client" % (exp_str)
        print(emsg)

    # deregister with redis
    redis_db.connection_pool.disconnect()
