#
#  Plex Plug-in Framework
#  Copyright (C) 2008-2012 Plex, Inc. (James Clarke, Elan Feingold). All Rights Reserved.
#

from systemservice import SystemService

class PlayerService(SystemService):
  def __init__(self, system):
    SystemService.__init__(self, system)
    Log.Debug("Starting the player service")
    
    Route.Connect("/system/players/{player}/{player_controller}/{command}", self.process_remote_command)
    
  def process_remote_command(self, player, player_controller, command, **kwargs):
    try:
      # Capitalise the first letter of the args so they match the attribute names
      player_controller = player_controller[0].upper()+player_controller[1:]
      command = command[0].upper()+command[1:]

      # Get a player object
      player_obj = Player[player]

      # Find & call the requested function
      if hasattr(player_obj, player_controller):
        controller = getattr(player_obj, player_controller)
        if hasattr(controller, command):
          cmd = getattr(controller, command)
          result = cmd(**kwargs)
          
          if player_controller.lower() == 'application' and command.lower() == 'screenshot':
            return DataObject(result, 'image/jpeg')
            
          else:
            return ''
            
        else:
          Log("%s has no attribute named '%s'" % (repr(controller), command))
      else:
        Log("%s has no controller named '%s'" % (repr(player_obj), player_controller))

    except FrameworkException:
      Log("Unable to access player '%s'" % player)