# -*- coding: utf-8 -*-
"""Never wait without seeing why (docs/plan/genre-browser/000 §Závazná pravidla): Kodi's own background progress
(xbmcgui.DialogProgressBG, like wcs/skin/installer.py) for every load the user waits for. It opens on the first update,
so a load from the cache shows nothing, and it always closes, also after an error."""
import xbmcgui


class Progress(object):
    def __init__(self, heading):
        self.heading = heading
        self.dialog = None

    def update(self, percent, message):
        if self.dialog is None:
            self.dialog = xbmcgui.DialogProgressBG()
            self.dialog.create(self.heading, message)
        self.dialog.update(max(0, min(100, int(percent))), self.heading, message)

    def close(self):
        if self.dialog is not None:
            try:
                self.dialog.close()
            finally:
                self.dialog = None

    def __enter__(self):
        return self

    def __exit__(self, *_exc):
        self.close()
        return False


def steps(progress, start, end):
    """A callback (done, total, message) mapping a sub-task onto start..end percent of `progress`."""
    def report(done, total, message):
        share = float(done) / total if total else 1.0
        progress.update(start + (end - start) * share, message)
    return report
