# -*- 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.

from elisa.core import log

class WindowsMessagesHandler(log.Loggable):

    def __init__(self, viewport):
        super(WindowsMessagesHandler, self).__init__()
        self.viewport = viewport
        self._signal_id = self.viewport.connect("win32-message-event",
                                                self._on_windows_message)
        self._wndprocs = {}

    def add_wndproc(self, signal_id, callback):
        """
        Add a new window proc handler to the viewport windows messages handler.

        @param signal_id: windows signal ID
        @type signal_id: C{int}
        @param callback: callable(viewport, event) to call when signal is
                         received by the viewport
        @type callback: C{callable}
        """
        msg_filter = self.viewport.get_message_filter()
        if signal_id in msg_filter:
            raise ValueError("Signal already handled")

        self._wndprocs[signal_id] = callback
        msg_filter.append(signal_id)
        self.viewport.set_message_filter(msg_filter)

    def remove_wndproc(self, signal_id):
        """
        Remove a window proc handler from the viewport windows messages handler.

        @param signal_id: windows signal ID
        @type signal_id: C{int}
        """
        msg_filter = self.viewport.get_message_filter()
        if signal_id in msg_filter:
            msg_filter.remove(signal_id)
            self.viewport.set_message_filter(msg_filter)
            del self._wndprocs[signal_id]

    def _on_windows_message(self, viewport, event):
        if event.message in self._wndprocs:
            return self._wndprocs[event.message](viewport, event)

    def clean(self):
        self.viewport.disconnect(self._signal_id)
        self._wndprocs = {}
        self.viewport.set_message_filter([])
