#!/usr/bin/python

from __future__ import with_statement
import os, sys
from optparse import OptionParser
import ConfigParser

import boss_info

def _print_details(bi, procs):
    """ Print query result with more details
    """
    for proc in procs:
        print 'Process: %s, \tbuildid: %s' % (proc, bi.get_imgtask_buildid(proc))
        print '\tDispatch at:', bi.get_imgtask_starttime(proc)
        print

        imgs = bi.get_imgtask_imgs(proc)
        for img in imgs:
            print '\timage: %s, status: %s' % (img, bi.get_img_status(proc, img))

        print

def _q_current(bi):
    """ Query current running process and the status of its image
        tasks.
        No argument.
    """
    procs = bi.get_running_imgtasks()
    if procs:
        _print_details(bi, procs)
    else:
        print "No process running"

def _q_allproc(bi):
    """ Query process and the status of its image tasks.
        No argument
    """
    procs = bi.get_all_imgtasks()
    if procs:
        _print_details(bi, procs)
    else:
        print "No process in history"

VERBOSE = False

# default redis server address
REDIS_SERVER = '127.0.0.1'

# command->function table
# TODO: use cmdln
CMDS = {
        'current': _q_current,
        'allproc': _q_allproc,
       }

if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option("-v", "--verbose", action="store_true",
                      help="print out verbose message for debugging")
    parser.add_option("-s", "--server", default=REDIS_SERVER,
                      help="specify address of redis server")


    (opts, args) = parser.parse_args()

    if opts.verbose:
        VERBOSE = True

    if not args or args[0] not in CMDS:
        print 'Must specify subcommand as command line argument. Supported subcommands:'
        print '\t%s' % ', '.join(CMDS.keys())
        sys.exit(0)

    bi = boss_info.BossInfo('redis://%s' % opts.server)

    cmd = args[0]
    # launch subcommand function
    CMDS[cmd](bi)

