# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 2006-2009 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Moovida with Fluendo's plugins.
#
# The GPL part of Moovida is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Moovida" in the root directory of this distribution package
# for details on that license.
#
# Authors: Gernot Klimscha <gernot@fluendo.com>

"""
StreamzapInputProvider component class
"""

from elisa.core import common
from elisa.core.components.input_provider import PushInputProvider
from elisa.core.input_event import *
from elisa.plugins.pigment.message import PigmentFrontendLoadedMessage

# win32api
import win32api

# streamzap message
WM_STREAMZAP = win32api.RegisterWindowMessage("3E4CA449-C26F-47c6-A124-D66589CFA12F")

class StreamzapInput(PushInputProvider):
    """
    This class implements Streamzap remote control support for win32
    """

    # TODO: support for volume keys
    convert_table = {
        14 : EventValue.KEY_GO_UP,
        15 : EventValue.KEY_GO_DOWN,
        16 : EventValue.KEY_GO_LEFT,
        17 : EventValue.KEY_GO_RIGHT,
        19 : EventValue.KEY_MENU,
        18 : EventValue.KEY_OK,
         0 : EventValue.KEY_EXIT,
         6 : EventValue.KEY_PLAY,
         7 : EventValue.KEY_PAUSE,
         8 : EventValue.KEY_STOP,
        13 : EventValue.KEY_SEEK_FORWARD,
        12 : EventValue.KEY_SEEK_BACKWARD,
        11 : EventValue.KEY_NEXT,
        10 : EventValue.KEY_PREVIOUS,
        }
    
    def initialize(self):
        dfr = super(StreamzapInput, self).initialize()
        bus = common.application.bus
        bus.register(self._frontend_loaded, PigmentFrontendLoadedMessage)
        return dfr

    def _frontend_loaded(self, msg, frontend):
        frontend.windows_msg_handler.add_wndproc(WM_STREAMZAP,
                                                 self._got_win32_message)

    def _got_win32_message(self, frontend, event):
        return self.create_input_event(event.message, event.wparam,
                                       event.lparam)

    def unbind(self):
        self.info("Streamzap input provider is shutting down")

    def create_input_event(self, msg, wparam, lparam):
        self.info("Callback create_input_event called")
        evt = None
        data = wparam
        if data and data in self.convert_table:
            self.info("Supported key code received: %d", data)
            evt = InputEvent(EventSource.REMOTE, EventType.OTHER,
                             self.convert_table[data])
            self.input_manager.process_event(evt)
            return True
        else:
            self.info('Unsupported key code received: %d', data)
            return False
