# -*- coding: utf-8 -*-
"""Busy indicator shown while Earth Engine requests are running."""

from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QApplication, QProgressDialog

from .dialog_theme import apply_dialog_theme

TITLE = u'Sentinel-2 / Processing — Đang xử lý'


class BusyProgress(object):
    """
    Modal, indeterminate progress dialog.

    Earth Engine calls (``getInfo``) and ``Map.addLayer`` must run on the GUI
    thread, so the dialog is repainted by pumping the event loop between steps
    instead of moving the work to a worker thread.
    """

    def __init__(self, parent, title=TITLE):
        dialog = QProgressDialog(u'', u'', 0, 0, parent)
        dialog.setWindowTitle(title)
        dialog.setCancelButton(None)
        dialog.setAutoClose(False)
        dialog.setAutoReset(False)
        dialog.setMinimumDuration(0)
        dialog.setWindowModality(Qt.WindowModality.WindowModal)
        dialog.setMinimumWidth(460)
        apply_dialog_theme(dialog)
        self._dialog = dialog

    def __enter__(self):
        self._dialog.show()
        QApplication.processEvents()
        return self

    def step(self, message):
        """Update the visible message and let Qt repaint."""
        self._dialog.setLabelText(message)
        QApplication.processEvents()

    def __exit__(self, exc_type, exc_value, traceback):
        self._dialog.reset()
        self._dialog.close()
        self._dialog.deleteLater()
        QApplication.processEvents()
        return False
