# -*- coding: utf-8 -*-
"""Background worker for loading administrative boundary datasets."""

from qgis.PyQt.QtCore import QThread, pyqtSignal

from .administrative_service import ensure_boundaries_loaded, is_boundaries_loaded


class BoundaryLoadWorker(QThread):
    progress_changed = pyqtSignal(int, str)
    load_finished = pyqtSignal(bool, str)

    def run(self):
        if is_boundaries_loaded():
            self.progress_changed.emit(100, '')
            self.load_finished.emit(True, '')
            return

        try:
            ensure_boundaries_loaded(self._emit_progress)
            self.load_finished.emit(True, '')
        except Exception as error:
            self.load_finished.emit(False, str(error))

    def _emit_progress(self, value, message):
        self.progress_changed.emit(value, message)
