# Orca
#
# Copyright 2010 Informal Informatica LTDA.
# Author: Jose Vilmar <vilmar@informal.com.br>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., Franklin Street, Fifth Floor,
# Boston MA  02110-1301 USA.

"""Module for notification messages"""
__id__        = "$Id$"
__version__   = "$Revision$"
__date__      = "$Date$"
__copyright__ = "Copyright (c) 2010 Informal Informatica LTDA."
__license__   = "LGPL"

import settings
import pyatspi
import input_event
import orca_state
import speech
import debug

from orca_i18n import _
from orca_i18n import C_
from orca_i18n import ngettext

# to store  the messages generated by the notification daemon
notificationMessages = []

# max size of the list
maxSizeList = 55

# a index to walk in the list of messages
indexNotificationMessages = 0

# when True the list mode is enabled
listNotificationMessagesModeEnabled = False

# number of keys invalid while in when in list notification mode.
# if > 3, call _help()
invalidKeys = 0

# input event handlers
inputEventHandlers = {}

def repeatLastNotificationMessage(script=None, inputEvent=None):
    """ Repeats the last notification message. """

    _showNotificationMessage(1)
    return True

def repeatPreviousNotificationMessage(script=None, inputEvent=None):
    """ Repeats the previous notification message. """

    _showNotificationMessage(2)
    return True

def enableNotificationMessageListMode(script=None, inputEvent=None):
    """ Enables the list of notification message. """

    _listModeEnable()
    return True

inputEventHandlers["repeatLastNotificationMessageHandler"] = \
        input_event.InputEventHandler(
            repeatLastNotificationMessage,
            # Translators: Orca can present the last notification message
            # to the user when the user presses a shortcut key.
            #
            _("Present last notification message."))

inputEventHandlers["repeatPreviousNotificationMessageHandler"] = \
        input_event.InputEventHandler(
            repeatPreviousNotificationMessage,
            # Translators: Orca can present the previous notification message
            # to the user when the user presses a shortcut key.
            #
            _("Present previous notification message."))

inputEventHandlers["enableNotificationMessageListModeHandler"] = \
        input_event.InputEventHandler(
            enableNotificationMessageListMode,
            # Translators: Orca can enable the notification messages
            # list mode when the user presses a shortcut key.
            #
            _("Present notification messages list"))

def _showMessage(msg):
    speech.speak(msg, None, True)
    orca_state.activeScript.displayBrailleMessage(msg, \
                   flashTime=settings.brailleFlashTime)

def saveMessage(msg):
    """save the message in a list to be presented later"""

    while size() >= maxSizeList:
        del notificationMessages[0]

    notificationMessages.append(msg)

    debug.println(debug.LEVEL_FINEST, \
                   "saveMessage (queue length: %s)"\
                   % (size()))

def size():
    """ return the size of the queue messages """

    return len(notificationMessages)

def _messagesPresent():

    if size() <= 0:
        # Translators: This is a brief message presented to the user
        # the list of notifications is empty.
        #
        msg = _("No notification messages")
        _showMessage(msg)
        return False

    return True

def _listModeEnable():
    """ enable the list mode if the queue is not empty """

    global indexNotificationMessages
    global listNotificationMessagesModeEnabled
    global invalidKeys
    if _messagesPresent():
        indexNotificationMessages = 1
        invalidKeys = 0
        listNotificationMessagesModeEnabled = True
        _help(True)
        _showNotificationMessage(indexNotificationMessages)

    return True

def _showNotificationMessage(index):
    global indexNotificationMessages
    if not _messagesPresent():
        return

    if index < 1:
        index = 1
        # Translators: This is a brief message presented to the user when
        # when the top of a list of notifications is reached.
        #
        msg = C_("notification", "Top")
        _showMessage(msg)
    elif index > size():
        index = size()
        # Translators: This is a brief message presented to the user when
        # when the bottom of a list of notifications is reached.
        #
        msg = C_("notification", "Bottom")
        _showMessage(msg)

    indexNotificationMessages = index
    index = size() - index
    debug.println(debug.LEVEL_FINEST, \
                   "_showNotificationMessage (queue length: %s, index: %s)"\
                   % (size(), index))
    if index >= 0 and index < size():
        msg = notificationMessages[index]
        _showMessage(msg)

def exitListNotificationMessagesMode():
    """ Turns list notification messages mode off. """

    global listNotificationMessagesModeEnabled
    listNotificationMessagesModeEnabled = False
    # Translators: Orca has a "List notification messages Mode" that allows
    # the user to list the latest notification messages received.
    # Escape exits this mode.
    # This string is the prompt which will be presented to the user 
    # in both speech and braille upon exiting this mode.
    #
    message = _("Exiting list notification messages mode.")
    _showMessage(message)

def listNotificationMessages(event):
    """ When list notification messages  mode is enabled, this function
    provides a means by which users can navigate through the list the
    notification messages. User can use the navigation keys or press
    the number of the message. Pressing escape key disable the mode.
    """

    global indexNotificationMessages
    global invalidKeys
    consumed = True
    speak = True

    if event.type != pyatspi.KEY_PRESSED_EVENT:
        return False
    speech.stop()
    if event.event_string == "Escape":
        exitListNotificationMessagesMode()
        speak = False
    elif event.event_string == "Home":
        indexNotificationMessages = 1
    elif event.event_string == "End":
        indexNotificationMessages = size()
    elif event.event_string == "Up":
        indexNotificationMessages -= 1
    elif event.event_string == "Down":
        indexNotificationMessages += 1
    elif event.event_string in\
                   [ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]:
        indexNotificationMessages = int(event.event_string)
    elif event.event_string in [ 'h', 'H']:
        _help(True)
        speak = False
    elif event.event_string == "space":
        pass
    else:
        speak = False
        invalidKeys += 1
        if invalidKeys > 2:
            _help()
            invalidKeys = 0

    if speak:
        _showNotificationMessage(indexNotificationMessages)
        invalidKeys = 0

    return consumed

def _help(longHelp = False):

    # Translators: This message inform to the user the number of
    # messages in the list.
    msg = ngettext("%d message.\n", "%d messages.\n", int(size())) % (size())
    # Translators: This is a help message.
    msg += _("Press h for help.\n")
    if longHelp:
        # Translators: The following string instructs the user how to navigate
        # amongst the list of commands presented in list notification 
        # messages mode as well as how to exit the list.
        #
        msg += \
            _("Use Up, Down, Home or End to navigate in the list.\n"\
              "Press Escape to exit.\n"\
              "Press Space to repeat the last message read.\n"\
              "Press one digit to read a specific message.\n")

    _showMessage(msg)
