# Copyright 2021 Vincent Texier <vit@free.fr>
#
# This software 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 3 of the License, or
# (at your option) any later version.
#
# This software 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 logging
import sys
import time
from typing import Callable, Optional, Set

from PyQt5.QtCore import (
    QObject,
    QThread,
    QTimer,
    pyqtSignal,
)
from PyQt5.QtWidgets import QApplication


class TaskWorker(QObject):
    """
    TaskWorker class
    """

    finished = pyqtSignal()

    def __init__(self, call: Callable) -> None:
        """
        Init TaskWorker instance

        :param call: Callable function
        """
        super().__init__()
        self.call = call

    def run(self):
        """
        Run call

        :return:
        """
        try:
            logging.debug(
                "Worker %s running in thread: %s",
                self.call.__name__,
                QThread.currentThread(),
            )
            self.call()
        except Exception as e:
            logging.exception("Worker %s failed: %s", self.call.__name__, str(e))
        self.finished.emit()


class ThreadManager(QObject):
    """
    ThreadManager2 class
    """

    finished = pyqtSignal()

    def __init__(self, parent: Optional[QObject] = None):
        """
        Init ThreadManager2 instance

        :param parent: Parent QObject instance
        """
        super().__init__(parent)
        self._active_workers: Set = set()

    def start(
        self, task_call: Callable, finished_call: Optional[Callable] = None
    ) -> TaskWorker:
        """
        Create a worker and run it in a separate thread

        :param task_call: Task function to run
        :param finished_call: Callback to run when task is finished
        :return:
        """
        worker = TaskWorker(task_call)
        self._active_workers.add(worker)

        thread = QThread()
        worker.moveToThread(thread)

        # Connecter
        thread.started.connect(worker.run)
        worker.finished.connect(thread.quit)
        worker.finished.connect(self.finished)

        if finished_call:
            worker.finished.connect(finished_call)

        # Nettoyage automatique
        def cleanup():
            if worker in self._active_workers:
                self._active_workers.remove(worker)

            if thread.isRunning():
                thread.quit()
                thread.wait(50)

            QTimer.singleShot(0, thread.deleteLater)
            QTimer.singleShot(0, worker.deleteLater)

        worker.finished.connect(cleanup)

        thread.start()
        return worker


if __name__ == "__main__":

    def my_call():
        """
        Test call
        :return:
        """
        print("wait 2 seconds...")
        time.sleep(2)

    def on_finished_call():
        """
        Test call on finished task
        :return:
        """
        print("task finished.")

    def my_call2():
        """
        Test call
        :return:
        """
        print("call 2 wait 2 seconds...")
        time.sleep(2)

    def on_finished_call2():
        """
        Test call on finished task
        :return:
        """
        print("task 2 finished.")

    # test one worker
    app = QApplication(sys.argv)

    manager = ThreadManager(app)
    manager.start(my_call, on_finished_call)
    manager.start(my_call2, on_finished_call2)

    QTimer.singleShot(5000, app.quit)
    print("main thread activity...")

    app.exec_()
