#!/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

import gi
from gi.repository import GObject
from typing import Optional, Any, Callable, Tuple

from cthulhu import resource_manager

class SignalManager:
    def __init__(self, app: Any) -> None:  # app is CthulhuApp instance
        self.app: Any = app
        self.resourceManager: Any = self.app.getResourceManager()  # ResourceManager

    def registerSignal(
        self,
        signalName: str,
        signalFlag: GObject.SignalFlags = GObject.SignalFlags.RUN_LAST,
        closure: Any = GObject.TYPE_NONE,
        accumulator: Tuple = (),
        contextName: Optional[str] = None
    ) -> bool:
        # register signal
        ok = False
        if not self.signalExist(signalName):
            GObject.signal_new(signalName, self.app, signalFlag, closure, accumulator)
            ok = True
        resourceContext = self.resourceManager.getResourceContext(contextName)
        if resourceContext:
            resourceEntry = resource_manager.ResourceEntry('signal', signalName, signalName, signalName, signalName)
            resourceContext.addSignal(signalName, resourceEntry)
        return ok

    def signalExist(self, signalName: str) -> bool:
        return GObject.signal_lookup(signalName, self.app) != 0

    def connectSignal(
        self,
        signalName: str,
        function: Callable,
        profile: Any,
        param: Optional[Any] = None,
        contextName: Optional[str] = None
    ) -> Optional[int]:
        signalID = None
        try:
            if self.signalExist(signalName):
                tryFunction = resource_manager.TryFunction(function)
                signalID = self.app.connect(signalName, tryFunction.runSignal)
                resourceContext = self.resourceManager.getResourceContext(contextName)
                if resourceContext:
                    resourceEntry = resource_manager.ResourceEntry('subscription', signalID, function, tryFunction, signalName)
                    resourceContext.addSubscription(signalName, function, resourceEntry)
            else:
                print('signal {} does not exist'.format(signalName))
        except Exception as e:
            print(e)

        return signalID

    def disconnectSignalByFunction(self, function: Callable, contextName: Optional[str] = None) -> bool:
        ok = False
        try:
            self.app.disconnect_by_func(function)
            ok = True
        except:
            pass
        resourceContext = self.resourceManager.getResourceContext(contextName)
        if resourceContext:
            resourceContext.removeSubscriptionByFunction(function)
        return ok

    def emitSignal(self, signalName: str, *args: Any) -> None:
        # emit a signal with optional arguments
        try:
            self.app.emit(signalName, *args)
            print('after Emit Signal: {}'.format(signalName))
        except:
            print('Signal "{}" does not exist.'.format(signalName))
