from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from qgis.core import *
#from PyQt5.QtWidgets import QProgressBar
import time
from qgis.core import (
     QgsApplication, QgsTask, QgsMessageLog,
     )
from Mapa_PU.kontroler import komunikaty

class Job():
    
    def start(self,progress):
        for i in range(21):#range (21):
            time.sleep(0.5)
            val = i * 5
            progress(val)

class TestTask(QgsTask):
    """Here we subclass QgsTask"""
    def __init__(self, desc,object):
        QgsTask.__init__(self, desc)
        self.object=object
        self.iface=iface
    def run(self):
        """This function is where you do the 'heavy lifting' or implement
        the task which you want to run in a background thread. This function 
        must return True or False and should only interact with the main thread
        via signals"""
        self.object.start(self.setProgress)
        #raise Exception("AAAAAAAAAAAAAAAA")
#         for i in range(21):#range (21):
#             time.sleep(0.5)
#             val = i * 5
#             #report progress which can be received by the main thread
#             self.setProgress(val)
#             #check to see if the task has been cancelled
#             if self.isCanceled():
#                 return False
        return True

    def finished(self, result):
        """This function is called automatically when the task is completed and is
        called from the main thread so it is safe to interact with the GUI etc here"""
        pass
#         if result is False:
#             iface.messageBar().pushMessage('Task was cancelled')
#         else:
#             iface.messageBar().pushMessage('Task Complete')
        


class Test():
    
    def __init__(self,iface):
        self.iface=iface
    
    def start(self):
        panel = self.iface.messageBar().createMessage('Kontrola danych','',self.iface.mainWindow() )
         
        pasek = QProgressBar()
        pasek.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        
        panel.layout().addWidget(pasek)
         
        self.iface.messageBar().pushWidget(panel,Qgis.Info)
        
        self.task = TestTask('Custom Task',Job())
        #self.task.begun.connect(self.completed)
        self.task.progressChanged.connect(lambda:pasek.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)
        
        
    def completed(self):
        komunikaty.informacja("AAAAA","BBBB")
            
class My_Dialog(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.resize(500, 350)
        self.lbl_info = QLabel('Info:', self)
        self.lbl_info.move(100, 50)
        self.edit_info = QLineEdit(self)
        self.edit_info.move(200, 50)
        lbl_prog = QLabel('Task Progress: ', self)
        lbl_prog.move(100, 210)
        self.prog = QProgressBar(self)
        self.prog.resize(200, 30)
        self.prog.move(200, 200)
        btn_OK = QPushButton('OK', self)
        btn_OK.move(300, 300)
        btn_OK.clicked.connect(self.newTask)
        btn_close = QPushButton('Close',self)
        btn_close.move(400, 300)
        btn_close.clicked.connect(self.close_win)
        btn_cancel = QPushButton('Cancel Task', self)
        btn_cancel.move(50, 300)
        btn_cancel.clicked.connect(self.cancelTask)


    def newTask(self):
        """Create a task and add it to the Task Manager"""
        self.task = TestTask('Custom Task')
        #connect to signals from the background threads to perform gui operations
        #such as updating the progress bar
        self.task.begun.connect(lambda: self.edit_info.setText('Working...'))
        self.task.progressChanged.connect(lambda: self.prog.setValue(self.task.progress()))
        self.task.taskCompleted.connect(self.completed)
        #self.task.taskCompleted.connect(lambda: self.edit_info.setText('Task Complete'))
        self.task.taskTerminated.connect(self.TaskCancelled)
        QgsApplication.taskManager().addTask(self.task)

    def cancelTask(self):
        self.task.cancel()

    def TaskCancelled(self):
        self.prog.setValue(0)
        self.edit_info.setText('Task Cancelled')

    def close_win(self):
        My_Dialog.close(self)

    def completed(self):
        informacja("AAAAA","BBBB")

class ProgressBar:
    import random
    from time import sleep
    
    MESSAGE_CATEGORY = 'TaskFromFunction'
    
    def doSomething(task, wait_time):
        """
        Raises an exception to abort the task.
        Returns a result if success.
        The result will be passed, together with the exception (None in
        the case of success), to the on_finished method.
        If there is an exception, there will be no result.
        """
        QgsMessageLog.logMessage('Started task {}'.format(task.description()),
                                 MESSAGE_CATEGORY, Qgis.Info)
        wait_time = wait_time / 100
        total = 0
        iterations = 0
        for i in range(100):
            sleep(wait_time)
            # use task.setProgress to report progress
            task.setProgress(i)
            
            arandominteger = random.randint(0, 500)
            total += arandominteger
            iterations += 1
            # check task.isCanceled() to handle cancellation
            if task.isCanceled():
                stopped(task)
                return None
            # raise an exception to abort the task
            if arandominteger == 42:
                raise Exception('bad value!')
        return {'total': total, 'iterations': iterations,
                'task': task.description()}
    
    def stopped(task):
        QgsMessageLog.logMessage(
            'Task "{name}" was canceled'.format(
                name=task.description()),
            MESSAGE_CATEGORY, Qgis.Info)
    
    def completed(exception, result=None):
        """This is called when doSomething is finished.
        Exception is not None if doSomething raises an exception.
        result is the return value of doSomething."""
        if exception is None:
            if result is None:
                QgsMessageLog.logMessage(
                    'Completed with no exception and no result '\
                    '(probably manually canceled by the user)',
                    MESSAGE_CATEGORY, Qgis.Warning)
            else:
                QgsMessageLog.logMessage(
                    'Task {name} completed\n'
                    'Total: {total} ( with {iterations} '
                    'iterations)'.format(
                        name=result['task'],
                        total=result['total'],
                        iterations=result['iterations']),
                    MESSAGE_CATEGORY, Qgis.Info)
        else:
            QgsMessageLog.logMessage("Exception: {}".format(exception),
                                     MESSAGE_CATEGORY, Qgis.Critical)
            raise exception
       
        
    def test(self):
        task1 = QgsTask.fromFunction('Waste cpu 1', self.doSomething,
                             on_finished=self.completed, wait_time=4)
        
        return task1

class TestPlugin:
    def __init__(self, iface):
        self.iface = iface
        self.tm = QgsApplication.taskManager()

    def initGui(self):
        self.action = QAction('Test', self.iface.mainWindow())
        self.iface.addPluginToMenu('Test', self.action)
        self.action.triggered.connect(self.run)

    def unload(self):
        self.iface.removePluginMenu('Test', self.action)

    def run(self):
        task = TestTask('my task', 10)
        self.tm.addTask(task)

    def complete(self):
        QgsMessageLog.logMessage('Task finished')

    def error(self):
        QgsMessageLog.logMessage('Error occurred')
        