# -*- coding: utf-8 -*-

# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import sys
import calculate.contrib.progressbar as progressbar

class DoubleMarkerBar(progressbar.Bar):
    """
    Прогресс с двойным маркером
    """

    def update(self, pbar, width):
        left, marker, right = (progressbar.format_updatable(i, pbar) for i in
                               (self.left, self.marker, self.right))

        width -= len(left) + len(right)
        # Marker must *always* have length of 2
        count = int(float(pbar.currval) / pbar.maxval * width)
        marker = str(marker[:1] * (count - 1) +
                     (marker[1:] if count > 0 else ""))

        if self.fill_left:
            return '%s%s%s' % (left, marker.ljust(width, self.fill), right)
        else:
            return '%s%s%s' % (left, marker.rjust(width, self.fill), right)


class StubProgressBar(object):
    def update(self, percents):
        pass

    def finish(self):
        pass


class StubMessageBox(object):
    def critical(self, message):
        pass

    def warning(self, message):
        pass


def get_progress_bar(bartype="text", title=""):
    """
    Получить объект прогресс бар
    """
    if bartype == "text":
        return progressbar.ProgressBar(
            maxval=100,
            widgets=[DoubleMarkerBar(left="[", right="]", marker="=>"), " ",
                     progressbar.Percentage(), " ",
                     progressbar.Timer(
                         format="Time:%s")]).start()
    elif bartype == "gui":
        from cl_progressbar_gui import ClProgressDialog
        if ClProgressDialog:
            pbar = ClProgressDialog()
            pbar.setCancelButton(None)
            pbar.adjustSize()
            pbar.setWindowTitle(title.decode('utf-8'))
            pbar.setAutoClose(False)
            pbar.setAutoReset(False)
            pbar.setMaximum(0)
            pbar.setLabelText(title.decode('utf-8'))
            pbar.setTextVisible(False)
            pbar.setStyleSheet("QProgressBar {border:none; text-align: center;}")
            return pbar
    return StubProgressBar()


def get_message_box():
    """
    Получить message box
    """
    from cl_progressbar_gui import ClMessageBox
    if ClMessageBox:
        return ClMessageBox()
    else:
        return StubMessageBox()
