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

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

    This software allows commands to be generated for the mahali relay service.

"""

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

from mahali_common import *

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", "--queue",dest="channel",help="Use <channel> to select mahali pubsub command queue. (e.g. mahali-relay-command)")
    parser.add_option("-c", "--command",dest="command",help="Provide the <type>=<value> of a command to send to the channel. (e.g. set-power-state='on', exit='exit', etc.)")
    (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()

    # 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)

    if options.channel:
        channel = options.channel
    else:
        channel = 'mahali-relay-command'

    if options.command:
        cmd_type, cmd_val = string.split(options.command,'=')
        print cmd_type, cmd_val
    else:
        print "A command is required in the form <command>=<value>."
        sys.exit()

    try:
        # package as a dictionary
        mahali_send_event(redis_db, None, channel, 'command', cmd_type, cmd_val)

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

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

    # deregister with redis
    redis_db.connection_pool.disconnect()
