#!/usr/bin/env python

"""
interactive Cassandra Python shell

"""

try:
    from IPython.Shell import IPShellEmbed
except ImportError:
    print "[I]: IPython not found, falling back to default interpreter."

def runshell():
    import os
    os.environ['PYTHONINSPECT'] = '1'

try:
    runshell = IPShellEmbed([])
except NameError:
    pass

import pycassa, optparse
from pycassa.system_manager import *
from sys import stderr, exit

parser = optparse.OptionParser(usage='Usage: %prog [OPTIONS]')
parser.add_option('-k', '--keyspace', help='Cassandra keyspace name.')
parser.add_option('-H', '--host', help='Hostname.')
parser.add_option('-p', '--port', type="int", help='Thrift port number.')
parser.add_option('-u', '--user', help='Username (for simple auth).')
parser.add_option('-P', '--passwd', help='Password (for simple auth).')
parser.add_option('-S', '--streaming', help='Using streaming transport.',
                  action="store_false", dest='framed')
parser.add_option('-F', '--framed', 
                  help='Use framed transport.  Default transport.',
                  action="store_true", dest='framed')

(options, args) = parser.parse_args()

if not options.keyspace:
    print >>stderr, "You must specify a keyspace with -k/--keyspace."
    exit(1)

hostname = options.host and options.host or 'localhost'
port = options.port and options.port or 9160
framed = True if options.framed is None else options.framed
credentials = None

if options.user or options.passwd:
    if options.user and (not options.passwd):
        print >>stderr, "You must supply a password for username", options.user
        exit(1)
    if options.passwd and (not options.user):
        print >>stderr, "You need a user to go with that password!"
        exit(1)
    credentials = {'username': options.user, 'password': options.passwd}

pool = pycassa.QueuePool(keyspace=options.keyspace,
                         server_list=['%s:%d' % (hostname, port)],
                         credentials=credentials,
                         framed_transport=framed)

SYSTEM_MANAGER = pycassa.SystemManager('%s:%d' % (hostname, port), credentials, framed)

print """
Cassandra Interactive Python Shell

%s/%s:%d

Available column family instances:""" % (options.keyspace, hostname, port)

for cfname in SYSTEM_MANAGER.get_keyspace_description(options.keyspace).keys():
    cfinstance = pycassa.ColumnFamily(pool, cfname)
    exec('%s = cfinstance' % cfname.upper())
    spaces = " " * (25 - len(cfname))
    print " *", cfname.upper(), spaces, "(", cfname, ")"

print """
Schema definition tools and cluster information are available through SYSTEM_MANAGER.

Enjoy!"""

runshell()
