#!/usr/bin/env python

__revision__ = "$Id$"
__docformat__ = 'restructuredtext en'

import os, sys, logging, optparse

from pysqueezecenter.server import Server
from pysqueezecenter.player import Player

# Globals

logger = logging.getLogger(__name__)
LOG_HELP = ','.join(["%d=%s" % (4-x, logging.getLevelName((x+1)*10)) for x in xrange(5)])
LOG_FORMAT_CONS = '%(levelname)s: %(message)s'
LOG_FORMAT_FILE = '%(asctime)s %(name)s[%(process)d] %(levelname)10s %(message)s'
LOGLEVEL_DICT = { 1 : 50, 2:40, 3:20, 4:10, 5:1 }
DEFAULT_VERBOSITY = 3

VALID_COMMANDS = ["play", "stop", "pause", "unpause", "toggle", "next", "prev"
                  "volume_up", "volume_down", "mute", "unmute", "seek_to",
                  "forward", "rewind", "set_power_state", "set_volume",]

# Option Parsing

parser = optparse.OptionParser(usage="%prog or type %prog -h (--help) for help", description=__doc__, version="%prog" + __revision__)

parser.add_option("-v", action="count", dest="verbosity", default=DEFAULT_VERBOSITY, help="Verbosity. Add more -v to be more verbose (%s) [default: %%default]" % LOG_HELP)
parser.add_option("-l", "--logfile", dest="logfile", default=None, help = "Log to file instead of console" )
parser.add_option("-s", "--host", dest="host", default="localhost", help="Specify Hostname of SqueezeCenter [default: %default]")
parser.add_option("-n", "--port", dest="port", default="9090", help="Specify Port of SqueezeCenter [default: %default]")
parser.add_option("-u", "--username", dest="username", default=None, help="Specify Authorisation Username")
parser.add_option("-p", "--password", dest="password", default=None, help="Specify Authorisation Password")
parser.add_option("-d", "--device", dest="device", default=None, help="Specify SqueezePlayer Device MAC Address")

(options, args) = parser.parse_args()

# Logging Setup

verbosity = LOGLEVEL_DICT.get(int(options.verbosity), DEFAULT_VERBOSITY)

if options.logfile is None:
    logging.basicConfig(level=verbosity, format=LOG_FORMAT_CONS)
else:
    logfilename = os.path.normpath(options.logfile)
    logging.basicConfig(level=verbosity, format=LOG_FORMAT_FILE, filename=logfilename, filemode='a')
    print >> sys.stderr, "Logging to %s" % logfilename

# Main

sc = Server(hostname=options.host, port=options.port, username=options.username, password=options.password)

try:
    sc.connect()
except:
    logger.error("Cannot connect to SqueezeCenter (%s:%s)" % (options.host, options.port))
    sys.exit(1)

logger.info("SqueezeCenter Version: %s" % (sc.get_version()))

for p in sc.get_players():
    logger.info("Player:%s|%s|V:%i|M:%s|T:%s|C:%s|W:%s" % (p.id, p.name, p.get_volume(), p.get_mode(), p.get_time_elapsed(), p.is_connected, p.get_wifi_signal_strength()))

player = sc.get_player(options.device)

if options.device and not player:
    logger.error("Cannot find player %s" % (options.device));
    sys.exit(1)

if not args:
    sys.exit(0)

cmd = args[0].lower()
try:
    params = args[1:]
except IndexError:
    params = []

if player and cmd in VALID_COMMANDS:
    logger.debug("Command %s | Param: %s" % (cmd, params))
    func = getattr(player, cmd, None)
    try:
        func(*params)
    except ValueError:
        logger.error("Invalid parameter")
        sys.exit(1)
    except TypeError:
        logger.error("Incorrect number of parameters")
else:
    logger.error("Invalid command or no device: %s" % (cmd))
    sys.exit(1)

