# -*- coding: utf-8 -*-
from qgis.core import QgsApplication, QgsTask,Qgis
from PyQt5 import QtCore
from PyQt5.QtWidgets import QProgressBar
from Mapa_PU.kontroler import komunikaty

class Task(QgsTask):
    """Klasa reprezentująca zadanie"""
    def __init__(self,desc,object,iface):
        QgsTask.__init__(self, desc)
        self.__object=object
        self.iface=iface
        
    def run(self):
        """Metoda uruchamiana przy wykonywaniu zadania"""
        try:
            self.__object.start(self.setProgress)
            if self.isCanceled():
                return False
            return True
        except Exception as e:
            self.iface.messageBar().pushMessage("{}".format(e))
    def finished(self, result):
        """Metoda wywoływana pozakończeniu"""
        if result is False:
            self.iface.messageBar().pushMessage("{}".format(result))
        else:
            self.iface.messageBar().pushMessage('Task Complete')
    
class TaskProgress():
    """Klasa pomocnicza uruchamiająca zadanie z paskiem postępu"""
    def __init__(self,iface):
        self.__iface=iface
        
        
    
    def start(self,message,object):
        """Uruchomienie zadania z paskiem postępu"""
        try:
            self.task = Task('Custom Task',object,self.__iface)
            progress=self.create_progress(message)
            #self.task.begun.connect(self.completed)
            self.task.progressChanged.connect(lambda:progress.setValue(self.task.progress()))
            #self.task.progressChanged.connect(lambda:pasek.setValue())
            self.task.taskCompleted.connect(self.completed)
            #self.task.progressChanged.connect(pasek.setValue)
            QgsApplication.taskManager().addTask(self.task)
        except Exception as e:
            raise e
        
    def create_progress(self,message):
        """Utworzenie paska postępu"""
        try:
            self.__iface.messageBar().clearWidgets()
            panel = self.__iface.messageBar().createMessage(message,'',self.__iface.mainWindow())
            progress = QProgressBar()
            progress.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
            panel.layout().addWidget(progress)
            self.__iface.messageBar().pushWidget(panel,Qgis.Info)
            return progress
        except Exception as e:
            raise e
        
    def completed(self):
        """Metoda wywoływana po zakonczeniu zadania"""
        try:
            #self.__iface.messageBar().clearWidgets()
            komunikaty.informacja("AAAAA","BBBB")
        except Exception as e:
            raise e