# Copyright (C) 2019 Kai Willadsen <kai.willadsen@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or (at
# your option) any later version.
#
# This program 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import weakref


class WeakMethodCallback:

    def __init__(self, callback):
        self.weak_method = weakref.WeakMethod(callback)
        self.emitter = None
        self.handle_id = None

    def __call__(self, *args):
        callback = self.weak_method()
        print("called", callback)
        if callback is None:
            # At least one weak ref is pointing to a collected object
            if self.handle_id is not None:
                self.emitter.disconnect(self.handle_id)
                self.handle_id = None
                self.emitter = None
            print("I was weak")
            return

        return callback(*args)

    def connect_to(self, emitter, signal_name):
        callback = self.weak_method()
        if callback is None:
            # FIXME: possibly log an error or raise? it's probably bad...
            return

        self.emitter = emitter
        self.handle_id = emitter.connect(signal_name, self)
