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

# Copyright 2011-2013 Calculate Ltd. 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.
from calculate.lib.cl_progressbar import get_progress_bar, get_message_box
from calculate.lib.utils.colortext import TextState
import sys
from result_viewer import PreProgressState, ProgressState

Colors = TextState.Colors
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_core3', sys.modules[__name__])


class PreProgressStateGui(PreProgressState):
    """
    Задача запрошена как с прогрессом но проценты еще не обрабатывались
    """
    def addProgress(self, message):
        self.dotting()
        self.parent.printer("\n")
        self.parent.add_progressbar()
        self.parent.set_state("progress")


class ProgressStateGui(ProgressState):
    """
    Отображение для gui прогресса
    """
    def finish_and_clean(self):
        self.parent.progress.finish()
        self.parent.printer.up(1)("")
        self.parent.set_progressbar(None)

class ResultViewerDecorator(object):
    def __init__(self, rv):
        self.rv = rv
        for v in self.rv.states.values():
            v.parent = self

    def __getattr__(self, item):
        return getattr(self.rv, item)


class ProgressGui(ResultViewerDecorator):
    """
    Отображение прогресса в Qt диалогах
    """
    def __init__(self, rv):
        super(ProgressGui, self).__init__(rv)
        self.rv.states['pre-progress'] = PreProgressStateGui(self)
        self.rv.states['progress'] = ProgressStateGui(self)
        self.progress_title = ""

    def add_progressbar(self):
        self.set_progressbar(get_progress_bar("gui", self.progress_title))

    def startTask(self, message, progress=False, num=1):
        self.rv.startTask(message, progress, num)
        self.progress_title = message


class ErrorGui(ResultViewerDecorator):
    """
    Отображение ошибок через gui
    """
    def __init__(self, rv):
        super(ErrorGui, self).__init__(rv)
        self.messages = []

    def show_messages(self):
        get_message_box().critical("\n".join(self.messages).decode('utf-8'))

    def printERROR(self, message, onlyShow=None):
        self.rv.printERROR(message, onlyShow)
        if onlyShow != 'gui':
            if message:
                self.messages.append(message)

    def endFrame(self):
        self.rv.task_state.endFrame()
        if self.messages:
            self.show_messages()


class WarningGui(ResultViewerDecorator):
    """
    Отображение предупреждений через gui
    """
    def __init__(self, rv):
        super(WarningGui, self).__init__(rv)
        self.warnings = []

    def show_messages(self):
        get_message_box().warning("\n".join(self.warnings).decode('utf-8'))

    def printWARNING(self, message, onlyShow=None):
        self.rv.printWARNING(message, onlyShow)
        if onlyShow != 'gui':
            if message:
                self.warnings.append(message)

    def endFrame(self):
        self.rv.task_state.endFrame()
        if not self.messages and self.warnings:
            self.show_messages()
        elif self.messages:
            self.messages.extend(self.warnings)
            self.rv.show_messages()
