#!/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 chat module for Mumble."""

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

import re

import cthulhu.chat as chat
import cthulhu.keybindings as keybindings
import cthulhu.cthulhu_state as cthulhu_state
import cthulhu.settings_manager as settings_manager
from cthulhu.ax_object import AXObject
from cthulhu.ax_selection import AXSelection
from cthulhu.ax_utilities import AXUtilities

_settingsManager = settings_manager.getManager()


class Chat(chat.Chat):
    """Mumble-specific chat helpers."""

    def __init__(self, script):
        super().__init__(script, [])

        # Mumble can have more than nine recent messages that are useful to review.
        self.messageKeys = [
            "F1", "F2", "F3", "F4", "F5", "F6",
            "F7", "F8", "F9", "F10", "F11", "F12",
        ]
        self.messageKeyModifier = keybindings.CTHULHU_MODIFIER_MASK
        self.inputEventHandlers = {}
        self.setupInputEventHandlers()
        self.keyBindings = self.getKeyBindings()
        self.messageListLength = len(self.messageKeys)
        self._conversationList = chat.ConversationList(self.messageListLength)

        self._channelTree = None

    def isChatRoomMsg(self, obj):
        if not obj:
            return False

        name = AXObject.get_name(obj)
        if name != "Activity log":
            return False

        if AXUtilities.is_label(obj) or AXUtilities.is_text(obj):
            return True

        return False

    def getMessageFromEvent(self, event):
        message = event.any_data or ""
        message = message.replace("\u2028", " ")
        message = re.sub(r"[\ufdd0-\ufdef]", "", message)
        message = " ".join(message.split())
        if not message:
            return ""

        if re.match(r"^\[\d{2}:\d{2}:\d{2}\]$", message):
            return ""

        message = re.sub(r"^\[\d{2}:\d{2}:\d{2}\]\s*", "", message)
        return message.strip()

    def _get_message_for_index(self, index):
        messageNumber = self.messageListLength - (index + 1)
        message, chatRoomName = None, None

        if _settingsManager.getSetting('chatRoomHistories'):
            conversation = self.getConversation(cthulhu_state.locusOfFocus)
            if conversation:
                message = conversation.getNthMessage(messageNumber)
                chatRoomName = conversation.name

        if not message:
            message, chatRoomName = \
                self._conversationList.getNthMessageAndName(messageNumber)

        return message, chatRoomName

    def getChatRoomName(self, obj):
        channelName = self._get_selected_channel_name()
        return channelName or "Mumble"

    def _get_selected_channel_name(self):
        channelTree = self._get_channel_tree()
        if not channelTree:
            return ""

        selectedChildren = AXSelection.get_selected_children(channelTree)
        for child in selectedChildren:
            childName = AXObject.get_name(child)
            if not childName:
                continue
            if childName.lower().startswith("channel "):
                return childName.replace("channel ", "", 1).strip()

        for child in selectedChildren:
            channelAncestor = AXObject.find_ancestor(
                child,
                lambda x: (AXObject.get_name(x) or "").lower().startswith("channel ")
            )
            if channelAncestor:
                ancestorName = AXObject.get_name(channelAncestor)
                return ancestorName.replace("channel ", "", 1).strip()

        return ""

    def _get_channel_tree(self):
        if self._channelTree and not AXUtilities.is_defunct(self._channelTree):
            return self._channelTree

        activeWindow = cthulhu_state.activeWindow
        if not activeWindow:
            return None

        def is_channels_tree(obj):
            return AXUtilities.is_tree(obj) and AXObject.get_name(obj) == "Channels and users"

        self._channelTree = AXObject.find_descendant(activeWindow, is_channels_tree)
        return self._channelTree
