import shutil
import sys

from . import logger

class DefaultProgressProvider:
    """
    Default progress provider implementation, which draws progress
    bar in the console, unless current logging is set to evrbose mode.
    """
    def progress(self, count, total, prefix="", suffix=""):
        if logger.VERBOSE:
            return

        size = shutil.get_terminal_size((80, 20))

        if prefix != "":
            prefix = prefix + "    "
        if suffix != "":
            suffix = "    " + suffix

        bar_len = size.columns - len(prefix) - len(suffix) - 10
        filled_len = int(round(bar_len * count / float(total)))

        percents = round(100.0 * count / float(total), 1)
        bar = '=' * filled_len + '-' * (bar_len - filled_len)

        sys.stdout.write('%s[%s] %s%%%s\r' % (prefix, bar, percents, suffix))
        sys.stdout.flush()

    def clear(self):
      if logger.VERBOSE:
          return

      size = shutil.get_terminal_size((80, 20))
      sys.stdout.write(" " * size.columns + "\r")
      sys.stdout.flush()

    def step(self, step_name):
        pass

    def scene(self, scene_name):
        pass

    def scene_stats(self, scene_name, stats):
        pass

    def render_process(self, process):
        pass

    def is_canceled(self):
        return False


PROGRESS_PROVIDER = DefaultProgressProvider()


def progress(count, total, prefix="", suffix=""):
    """
    Report new progress status of the current task.
    """
    PROGRESS_PROVIDER.progress(count, total, prefix, suffix)


def progressClear():
    """
    Clear all possible progress bar lines in the ocnsole.
    """
    PROGRESS_PROVIDER.clear()


def step(step_name):
    PROGRESS_PROVIDER.step(step_name)


def scene(scene_name):
    PROGRESS_PROVIDER.scene(scene_name)

def scene_stats(scene_name, stats):
    PROGRESS_PROVIDER.scene_stats(scene_name, stats)

def render_process(process):
    PROGRESS_PROVIDER.render_process(process)

def is_canceled():
    return PROGRESS_PROVIDER.is_canceled()


def setProvider(provider):
    """
    Override progress provider with a given name.
    Is used by glue logic to hijack progress and do smart things.
    """
    global PROGRESS_PROVIDER
    PROGRESS_PROVIDER = provider


def restoreDefaultProvider():
    """
    Restore default progress provider.
    """
    global PROGRESS_PROVIDER
    PROGRESS_PROVIDER = DefaultProgressProvider()
