#!/usr/bin/env python

# This script implements basic controls for a Boxee xbmc device
# Play both pauses and plays a video.
# Everything else should be straightforward

import argparse
import sys
import urllib2


def cli_parser():

    # Command line argument parser
    parser = argparse.ArgumentParser(
        add_help=False,
        description="Boxee_Control is a script that lets you control Boxee and XBMC devides. Supported commands are Play/Pause, OK/Enter, Stop, Left, Right, Down, Up.")
    parser.add_argument(
        "--ip", metavar='192.168.199.23',
        help="IP address of boxee/xbmc device.")
    parser.add_argument(
        "--port", metavar='8800', default='8800',
        help="Specify port value, default is 8800.")
    parser.add_argument(
        "--command", '-c', metavar="Play",
        help="Command to issue. Supported Commands: Play, Pause, Stop, Left, Right, Down, Up, Ok, Enter, Rewind, Fastforward.")
    parser.add_argument(
        '-h', '-?', '--h', '-help', '--help', action="store_true",
        help=argparse.SUPPRESS)
    args = parser.parse_args()

    if args.h:
        parser.print_help()
        sys.exit()

    return args

if __name__ == '__main__':

    # Begin parsing command line options
    cli_args = cli_parser()

    xbmc_system = "http://" + cli_args.ip + ":" + cli_args.port

    if cli_args.command.lower().strip() == "play" or cli_args.command.lower().strip() == "pause":
        xbmc_command = '/xbmcCmds/xbmcHttp?command=Pause()'
    elif cli_args.command.lower() == "stop":
        xbmc_command = '/xbmcCmds/xbmcHttp?command=Stop()'
    elif cli_args.command.lower() == "ok" or cli_args.command.lower() == "enter":
        xbmc_command = '/xbmcCmds/xbmcHttp?command=SendKey(0XF00D)'
    elif cli_args.command.lower() == "right":
        xbmc_command = '/xbmcCmds/xbmcHttp?command=SendKey(0XF027)'
    elif cli_args.command.lower() == "left":
        xbmc_command = '/xbmcCmds/xbmcHttp?command=SendKey(0XF025)'
    elif cli_args.command.lower() == "down":
        xbmc_command = '/xbmcCmds/xbmcHttp?command=SendKey(0XF028)'
    elif cli_args.command.lower() == "up":
        xbmc_command = '/xbmcCmds/xbmcHttp?command=SendKey(0XF026)'
    elif cli_args.command.lower() == "rewind":
        xbmc_command = '/xbmcCmds/xbmcHttp?command=Action(78)'
    elif cli_args.command.lower() == "fastforward":
        xbmc_command = '/xbmcCmds/xbmcHttp?command=Action(77)'
    else:
        print "You didn't specify a supported command.  Please only use:"
        print "play, pause, ok, enter, up, down, left, right, rewind, or fastworward"
        sys.exit()

    full_url = xbmc_system + xbmc_command

    # Send the command
    urllib2.urlopen(full_url)
