#!/usr/bin/env python2.7
import shelve
import os
import sys
import PyBullet
import argparse
import readline

def get_api_obj(s):
    bullet = None
    try:
        if s.has_key('BulletAPI') and s['BulletAPI']:
            bullet = s['BulletAPI']
        else:
            print >> sys.stderr, 'No API Key stored, please enter your API Key to use this script.'
            print >> sys.stderr, 'You can get it @ https://www.pushbullet.com/account'
            print >> sys.stderr, "API Key: ",
            api_key = raw_input()
            bullet = PyBullet.PyBullet(api_key)
            s['BulletAPI'] = bullet
    except Exception, e:
        print e
        s.close()
    finally:
        return bullet

if os.environ.has_key('XDG_CONFIG_HOME'):
    XDG_CONFIG=os.environ['XDG_CONFIG_HOME']
else:
    XDG_CONFIG=os.path.join(os.environ['HOME'], ".config/")

SHELVE = shelve.open(os.path.join(XDG_CONFIG, "pybullet.db"), writeback=True)
BULLET = get_api_obj(SHELVE)

def devices(args):
    for device in BULLET.updateDevices():
        print device.nick

def push(args):
    device = args.device
    type = args.type
    data= {}
    attr = BULLET.getTypeAttr(type)
    if args.title and args.content:
        data[attr[0]] = args.title
        data[attr[1]] = args.content
    else:
        print "Content of your push not specified in cli, please enter it now:"
        data[attr[0]] = raw_input(attr[0].capitalize() + ": ")
        print attr[1].capitalize() + ": (Press CTRL + D when you're done)"
        raw = []
        try:
            while True:
                line = raw_input(">> ")
                raw.append(line + '\n')
        except EOFError:
            print "EOF"
        data[attr[1]] = "".join(raw).strip('\n')
    BULLET.push(device, type, **data)

def get_api_key(args):
    print BULLET.getApiKey()

def update_api_key(args):
    BULLET.updateApiKey(args.key)

def types(args):
    for type in BULLET.getTypes():
        print type,
    print

if __name__ == "__main__":

    # create the toplevel parser
    parser = argparse.ArgumentParser(prog='bullet',
                                     description="PushBullet CLI Interface.",
                                     formatter_class=argparse.
                                     RawDescriptionHelpFormatter)
    subparsers = parser.add_subparsers(title="subcommands",
                                       metavar="<command>",
                                       help="bullet subcommands")
    subparsers.required = True

    # create the parser for the "devices" command
    dev_parser = subparsers.add_parser('devices', help="get devices list")
    dev_parser.set_defaults(func=devices)

    # create the parser for the "types" command
    type_parser = subparsers.add_parser('types', help="get push types")
    type_parser.set_defaults(func=types)

    # create the parser for the "push" command
    push_parser = subparsers.add_parser('push', help="push to a device")
    push_parser.set_defaults(func=push)
    push_parser.add_argument('device', help="device you want to push to.")
    push_parser.add_argument('type', nargs='?', default='note', help="type of your push. (default = note)")
    push_parser.add_argument('title', nargs='?', help="title of your push.")
    push_parser.add_argument('content', nargs='?', help="content of your push.")

    # create the parser for the "api" command
    api_parser = subparsers.add_parser('api', help="manage your api key")
    api_subparsers = api_parser.add_subparsers(title="subcommands",
                                               metavar="<command>",
                                               help="api subcommands")

    # create the parser for the "api display" command
    get_key_parser = api_subparsers.add_parser('display', help="display the current stored API Key")
    get_key_parser.set_defaults(func=get_api_key)

    # create the parser for the "api update" command
    update_key_parser = api_subparsers.add_parser('update', help="update your stored API Key")
    update_key_parser.add_argument('key', help="your new API Key")
    update_key_parser.set_defaults(func=update_api_key)

    # parse args and call the desired functions
    args = parser.parse_args()
    args.func(args)

    # finnaly close shelve
    SHELVE.close()
