import sys
import time
import math
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QPushButton, QProgressBar
from PyQt5.QtWidgets import QVBoxLayout, QMessageBox
from q_progress_thread import QProgressThread


class QRunnerProgressBar(QWidget):
    def __init__(self, count, tip, runner):
        super(QRunnerProgressBar, self).__init__()
        self.setWindowTitle('QRunnerProgressBar')

        self.vbox = QVBoxLayout()

        self.btn = QPushButton(tip)
        self.btn.clicked.connect(self.on_btn_click)
        self.vbox.addWidget(self.btn)

        self.pbar = QProgressBar(self)
        self.pbar.setValue(0)
        self.vbox.addWidget(self.pbar)

        self.setLayout(self.vbox)
        self.resize(300, 100)
        self.show()

        self.count = count
        self.runner = runner

    def on_btn_click(self):
        self.thread = QProgressThread(self.runner)
        self.thread.connect(self.on_progress)
        self.thread.start()
        self.btn.setEnabled(False)

    def on_progress(self, info):
        percent_value = int(math.floor(info.progress*100/self.count))
        self.pbar.setValue(int(percent_value))
        self.setWindowTitle(info.msg)
        if self.pbar.value() == 100:
            self.pbar.setValue(0)
            self.btn.setEnabled(True)
            self.setWindowTitle('QRunnerProgressBar')

    def closeEvent(self, event):
        self.thread = None


if __name__ == "__main__":
    app = QApplication(sys.argv)

    def on_run(emit_progress):
        for i in range(0, 5):
            time.sleep(1)
            emit_progress(i+1, f'Python技能树->PyQT:{i+1}/5')

    p = QRunnerProgressBar(
        count=5,
        tip='看资料+做题，就有技能树进度',
        runner=on_run
    )
    sys.exit(app.exec_())
