# -*- coding: utf-8 -*-

# async guidance from
#  https://martinfitzpatrick.name/article/multithreading-pyqt-applications-with-qthreadpool/
# (didn't use inbuilt python async/await since it requires an event/thread loop which it seems
#  qt itself isn't playing nice with... maybe?)


from PyQt5.QtCore import QRunnable, pyqtSlot, QThreadPool

threadpool = QThreadPool()
print("Multithreading with maximum %d threads" % threadpool.maxThreadCount())

class Worker(QRunnable):
    '''
    Worker thread

    Inherits from QRunnable to handler worker thread setup, signals and wrap-up.

    :param callback: The function callback to run on this worker thread. Supplied args and
                     kwargs will be passed through to the runner.
    :type callback: function
    :param args: Arguments to pass to the callback function
    :param kwargs: Keywords to pass to the callback function

    '''

    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()
        # Store constructor arguments (re-used for processing)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs

    @pyqtSlot()
    def run(self):
        '''
        Initialise the runner function with passed args, kwargs.
        '''
        self.fn(*self.args, **self.kwargs)

