#!/usr/bin/env python3
#
# Copyright (c) 2024 Stormux
# Copyright (c) 2010-2012 The Orca Team
# Copyright (c) 2012 Igalia, S.L.
# Copyright (c) 2005-2010 Sun Microsystems Inc.
#
# 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.
#
# Forked from Orca screen reader.
# Cthulhu project: https://git.stormux.org/storm/cthulhu

"""Custom script for Mumble."""

__id__        = "$Id$"
__version__   = "$Revision$"
__date__      = "$Date$"
__copyright__ = "Copyright (c) 2024 Stormux."
__license__   = "LGPL"

import time

import cthulhu.debug as debug
import cthulhu.scripts.toolkits.Qt.script as Qt
from cthulhu.ax_object import AXObject
from cthulhu.ax_utilities import AXUtilities

from .chat import Chat
from .script_utilities import Utilities


class Script(Qt.Script):
    """Mumble-specific script tweaks."""

    def __init__(self, app):
        self._lastConnectFocusName = ""
        self._lastConnectFocusRole = None
        self._lastConnectFocusTime = 0.0
        self._lastMessageDialogId = None

        super().__init__(app)

    def getChat(self):
        return Chat(self)

    def getUtilities(self):
        return Utilities(self)

    def setupInputEventHandlers(self):
        super().setupInputEventHandlers()
        self.inputEventHandlers.update(self.chat.inputEventHandlers)

    def getAppKeyBindings(self):
        return self.chat.keyBindings

    def getAppPreferencesGUI(self):
        return self.chat.getAppPreferencesGUI()

    def getPreferencesFromGUI(self):
        return self.chat.getPreferencesFromGUI()

    def onTextInserted(self, event):
        if self.chat.presentInsertedText(event):
            return

        super().onTextInserted(event)

    def onFocusedChanged(self, event):
        if self._should_ignore_connect_dialog_focus(event):
            return

        super().onFocusedChanged(event)

    def onCaretMoved(self, event):
        super().onCaretMoved(event)
        self._maybe_announce_message_dialog_input(event.source)

    def _should_ignore_connect_dialog_focus(self, event):
        if not event.detail1:
            return False

        obj = event.source
        if not self._is_in_connect_dialog(obj):
            return False

        objName = AXObject.get_name(obj) or ""
        if not objName:
            return False

        role = AXObject.get_role(obj)
        now = time.time()
        if self._lastConnectFocusName == objName \
           and self._lastConnectFocusRole == role \
           and (now - self._lastConnectFocusTime) < 0.35:
            msg = "MUMBLE: Ignoring duplicate focus event in connect dialog"
            debug.printMessage(debug.LEVEL_INFO, msg, True)
            return True

        self._lastConnectFocusName = objName
        self._lastConnectFocusRole = role
        self._lastConnectFocusTime = now
        return False

    def _is_in_connect_dialog(self, obj):
        dialog = AXObject.find_ancestor(obj, AXUtilities.is_dialog)
        return bool(dialog) and AXObject.get_name(dialog) == "Mumble Server Connect"

    def _maybe_announce_message_dialog_input(self, obj):
        if not obj or not AXUtilities.is_text(obj):
            return

        if not AXUtilities.is_editable(obj):
            return

        if AXObject.get_name(obj):
            return

        dialog = AXObject.find_ancestor(obj, AXUtilities.is_dialog)
        if not dialog:
            return

        dialogName = AXObject.get_name(dialog) or ""
        if not dialogName.startswith("Sending message to "):
            return

        dialogHash = hash(dialog)
        if dialogHash == self._lastMessageDialogId:
            return

        self._lastMessageDialogId = dialogHash
        label = "Message"
        voice = self.speechGenerator.voice(string=label)
        self.speakMessage(label, voice=voice)
