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

"""
/***************************************************************************
 dbpriskapp
                                 A QGIS plugin
 dbpriskapp
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-06-12
        copyright            : (C) 2025 by KIOS Smart Water Team
        email                : mkiria01@ucy.ac.cy
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'KIOS Smart Water Team'
__date__ = '2025-06-12'
__copyright__ = '(C) 2025 by KIOS Smart Water Team'

import traceback

import processing
from qgis.PyQt.QtCore import pyqtSignal
from qgis.core import QgsTask


class ProcessingTask(QgsTask):
    task_finished = pyqtSignal(object, object)  # Signal to emit task result and exception (If exist)

    def __init__(self, description, algorithm_id, parameters, feedback=None):
        super().__init__(description)
        self.desc = description
        self.algorithm_id = algorithm_id
        self.parameters = parameters
        self.result = None
        self.exception = None
        self.feedback = feedback

    def run(self):
        try:
            # Run the processing algorithm
            # print(self.algorithm_id)
            # print(self.parameters)
            self.result = processing.run(f'{self.algorithm_id}', self.parameters, feedback=self.feedback)

            return True  # Return True to indicate successful completion
        except Exception as e:
            stack_trace = traceback.format_exc()
            print(stack_trace)
            self.exception = e
            return False  # Return False to indicate failure

    def finished(self, result: bool):
        self.task_finished.emit(self.result, self.exception)  # Emit the result or exception when finished
