#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: brython (http://brython.info) (like python3)
#
# Imports =====================================================================
from browser import document


# Functions & classes =========================================================
class ProgressBar(object):
    """
    Generic progressbar controller.
    """
    def __init__(self, tag, whole_tag):
        self.tag = tag
        self.whole_tag = whole_tag
        self.original_message = tag.text

    @staticmethod
    def _compute_percentage(progress_tuple):
        """
        Compute percentage from (done / len(all)) tuple.
        """
        # division by zero..
        if progress_tuple[0] == 0:
            return 0

        return (100 / progress_tuple[1]) * progress_tuple[0]

    def show(self, progress, msg=None):
        """
        Show the progress bar and set it to `progress` tuple or value.

        Args:
            progress (tuple / int / float): Tuple ``(done / len(all))`` or
                the direct percentage value as int / float.
            msg (str, default None): Alternative background description.
        """
        if self.whole_tag.style.display == "none":
            self.whole_tag.style.display = "block"

        # allow either direct percentage value, or (done / len(all)) pairs
        if isinstance(progress, int) or isinstance(progress, float):
            percentage = progress
        else:
            percentage = self.__class__._compute_percentage(progress)

        # toggle animation
        self.tag.class_name = "progress-bar"
        if percentage < 100:
            self.tag.class_name += " progress-bar-striped active"
        else:
            msg = "Hotovo"

        # show percentage in progress bar
        self.tag.aria_valuemin = percentage
        self.tag.style.width = "{}%".format(percentage)

        if msg:
            self.tag.text = msg

    def hide(self):
        """
        Hide the progressbar.
        """
        self.whole_tag.style.display = "none"

    def reset(self):
        """
        Reset the progressbar to 0, hide it and set original text message at
        background.
        """
        self.hide()
        self.tag.class_name = "progress-bar progress-bar-striped active"
        self.tag.aria_valuemin = 0
        self.tag.style.width = "{}%".format(0)
        self.tag.text = self.original_message


URLBar = ProgressBar(
    tag=document["url_progressbar"],
    whole_tag=document["whole_url_progressbar"]
)
ISSNBar = ProgressBar(
    tag=document["issn_progressbar"],
    whole_tag=document["whole_issn_progressbar"]
)
AuthorBar = ProgressBar(
    tag=document["author_progressbar"],
    whole_tag=document["whole_author_progressbar"]
)