#!python

import argparse
import json
import os
import re
import sys
import yaml

from pushbullet import Pushbullet
from runbullet import parse_config_file


def print_usage():
    print ('''Usage: {} [-h|--help] <-t|--target <target name>> <-a|--action <action name>> payload
    -h, --help:\t\tShow this help and exit
    -t, --target:\tName of the target device/host
    -a, --action\tAction to run, it includes both the package name and the method (e.g. shell.exec or music.mpd.play)
    payload:\t\tArguments to the action
'''.format(sys.argv[0]))

def main():
    config = parse_config_file()
    API_KEY = config['pushbullet']['token']
    pb = Pushbullet(API_KEY)

    devices = [
        _ for _ in pb.devices if _.nickname == config['pushbullet']['device']
    ]

    if len(devices) > 0:
        device = devices[0]
    else:
        print('Device {} not found - please create a virtual device on ' +
              'your PushBullet account'.format(config['pushbullet']['device']))
        return

    parser = argparse.ArgumentParser()
    parser.add_argument('--target', '-t', dest='target', required=True,
                        help="Destination of the command")

    parser.add_argument('--action', '-a', dest='action', required=True,
                        help="Action to execute, as package.method")

    opts, args = parser.parse_known_args(sys.argv[1:])
    payload = {}

    if len(args) % 2 != 0:
        raise RuntimeError('Odd number of key-value options passed: {}'.
                           format(args))

    for i in range(0, len(args), 2):
        payload[re.sub('^-+', '', args[i])] = args[i+1]

    msg = {
        'target': opts.target,
        'action': opts.action,
        **payload,
    }

    print('msg: {}'.format(msg))
    pb.push_note('', json.dumps(msg), device)


if __name__ == '__main__':
    main()

# vim:sw=4:ts=4:et: