# -*- 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.

from __future__ import print_function
from __future__ import absolute_import
from calculate.consolegui import qt
from .more import LabelWordWrap, _print, get_system_rgb, ParameterWindow, dpivalue

DEBUG_LEVEL = 0


def debug(level, *args):
    if level <= DEBUG_LEVEL:
        for s in args:
            print(s, end=' ')
        print()


class MethodNameWgt(qt.QWidget):
    def __init__(self, parent, ClientObj):
        super().__init__(parent)
        self._parent = parent
        self.ClientObj = ClientObj

        # Set style
        self.setAttribute(qt.Qt.WA_StyledBackground)
        self.setObjectName('ControlButton')
        self.setStyleSheet("QWidget#ControlButton "
                           "{background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
                           "stop: 0 #111111, stop: 0.95 #777777, stop: 1 #666666);}")
        self.hlayout = qt.QHBoxLayout(self)
        self.hlayout.setAlignment(qt.Qt.AlignLeft | qt.Qt.AlignVCenter)
        self.hlayout.setContentsMargins(28, 0, 0, 0)
        self.hlayout.setSpacing(0)

        self.meth_name = qt.QLabel('Method Name', self)
        #        self.meth_name.setAlignment(qt.Qt.AlignLeft)
        self.meth_name.setStyleSheet("font-size: {}px;"
                                     "font: bold;"
                                     "color: white;".format(int(dpivalue(16))));

        #                                  "background-color: rgb(220,220,220);}"
        self.button_hover_style = "QPushButton:hover {" \
                                  "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1," \
                                  "stop: 0 #333333, stop: 1 #A0A0A9);}"
        #                                       "stop: 0 #404040, stop: 1 #A8A8B2);}"
        self.button_pressed_style = "QPushButton:pressed {" \
                                    "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1," \
                                    "stop: 0 #222222, stop: 1 #9797A0);}"

        self.hlayout.addWidget(self.meth_name)
        self.setLayout(self.hlayout)
        self.setFixedHeight(dpivalue(40))
        self.hide()
        self.button_widget = None


    def setMethodName(self, method_name):
        for meth_inf in self.ClientObj.methods_list:
            if meth_inf.string[1] == method_name:
                self.meth_name.setText(meth_inf.string[2])
                return
        self.meth_name.setText(method_name)

    def _hide(self):
        if self.button_widget:
            self.hlayout.removeWidget(self.button_widget)
            self.button_widget.close()
            self.button_widget = None
        self.hide()


# def set_button_style(self):
#        if hasattr (self, 'next_button'):
#            self.next_button.setStyleSheet("QPushButton {"
#            "color: white; margin 0px;"
#            "padding-left: 8px; padding-right: 8px;"
#            "border-left: 1px solid black; border-right: 1px solid black;"
#            "border-radius: 0px;"
#            "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.95,"
#                "stop: 0 #222222, stop: 1 #9797A0);}" + \
#                self.button_hover_style + self.button_pressed_style)
#        if hasattr (self, 'prev_button'):
#            self.prev_button.setStyleSheet("QPushButton {"
#            "color: white; margin 0px;"
#            "padding-left: 8px; padding-right: 8px;"
#            "border-left: 1px solid black;"
#            "border-radius: 0px;"
#            "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.95,"
#                "stop: 0 #222222, stop: 1 #9797A0);}" + \
#                self.button_hover_style + self.button_pressed_style)

class ControlButtonWgt(qt.QWidget):
    def __init__(self, parent, ClientObj):
        super().__init__(parent)
        self._parent = parent
        self.ClientObj = ClientObj

        # Set style
        self.setAttribute(qt.Qt.WA_StyledBackground)
        self.setObjectName('ControlButton')
        
        self.setStyleSheet("QWidget#ControlButton "
                           "{background-color: %s;}"%
                           get_system_rgb(self, ParameterWindow))

        self.main_layout = qt.QVBoxLayout(self)
        self.main_layout.setContentsMargins(28, 8, 0, 28)
        self.question_label = LabelWordWrap("")
        # self.question_label.hide()
        self.main_layout.addWidget(self.question_label)

        self.hlayout = qt.QHBoxLayout()
        self.hlayout.setAlignment(qt.Qt.AlignLeft | qt.Qt.AlignVCenter)
        self.hlayout.setContentsMargins(0, 0, 28, 0)
        self.hlayout.setSpacing(0)
        self.main_layout.addItem(qt.QSpacerItem(
            0, 0, qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding))
        self.main_layout.addLayout(self.hlayout)

        # self.setLayout(self.hlayout)
        self.setFixedHeight(dpivalue(90))
        self.hide()
        self.confirmWgt = None
        self.break_button = None

        self.button_widget = None
        self.next_button = None
        self.prev_button = None
        self.cancel_button = None
        self.customs = None
        self.default_button = None
        self.clear_proc_cache_button = None

    def set_confirm_question(self, message):
        self.question_label.setText(message)
        self.question_label.show()

    def set_confirmation(self, wgt):
        if self.confirmWgt:
            self.hlayout.removeWidget(self.confirmWgt)
        self.confirmWgt = wgt
        self.hlayout.insertWidget(0, wgt)

    def close_confirmation(self):
        self.question_label.hide()
        if self.confirmWgt:
            self.hlayout.removeWidget(self.confirmWgt)
            self.confirmWgt.close()
            self.confirmWgt = None

    def set_break_button(self, wgt):
        if self.break_button:
            self.break_button.close()
        self.break_button = wgt
        self.hlayout.addWidget(wgt)

    def close_break_button(self):
        if self.break_button:
            self.break_button.close()
            self.break_button = None

    def _hide(self):
        if self.button_widget:
            self.hlayout.removeWidget(self.button_widget)
            self.button_widget.close()
            self.button_widget = None
        self.hide()

    def add_custom_button(self, Group, x, y, brief=False,
                            next_button_text=""):
        # self.del_button()
        buttons = self._parent.MainFrameWgt.buttons
        self.button_widget = qt.QWidget(self)
        end_layout = qt.QHBoxLayout(self.button_widget)
        end_layout.setContentsMargins(0, 0, 0, 0)
        end_layout.setSpacing(10)
        end_layout.addItem(qt.QSpacerItem(
            0, 0, qt.QSizePolicy.Expanding, qt.QSizePolicy.Maximum))

        self.customs = []
        self.add_cancel_button(end_layout, Group, brief, next_button_text)
        has_next = False
        button = None
        for field, callback in buttons:
            if field.element == "button_next":
                self.add_next_button(end_layout, Group, brief, next_button_text)
                has_next = True
            else:
                button = qt.QPushButton(self)
                self.customs.append(button)
                # button.setText(field.label.decode('utf-8'))
                button.setText(field.label)
                button.clicked.connect(self.button_disabled)
                button.clicked.connect(callback)
                button.setMinimumWidth(62)
                button.setFixedHeight(dpivalue(32))
                if field.guitype == "readonly":
                    button.setDisabled(True)
                end_layout.addWidget(button)
        if not has_next and button:
            button.setShortcut(qt.QKeySequence(qt.Qt.Key_Return))
            button.setShortcut(qt.QKeySequence(qt.Qt.Key_Enter))
            self.default_button = button

        self.hlayout.addWidget(self.button_widget)

    def add_standart_button(self, Group, x, y, brief=False, \
                            next_button_text=""):
        # self.del_button()
        main_frame = self._parent.MainFrameWgt
        # add 1 (or 2) button ok (next) [and previous]
        self.button_widget = qt.QWidget(self)
        end_layout = qt.QHBoxLayout(self.button_widget)
        end_layout.setContentsMargins(0, 0, 0, 0)
        end_layout.setSpacing(10)
        end_layout.addItem(qt.QSpacerItem(
            0, 0, qt.QSizePolicy.Expanding, qt.QSizePolicy.Maximum))

        self.add_cancel_button(end_layout, Group, brief, next_button_text)
        self.add_prev_button(end_layout, Group, brief, next_button_text)
        self.add_next_button(end_layout, Group, brief, next_button_text)

        self.hlayout.addWidget(self.button_widget)
        x += 1
        return x

    def add_cancel_button(self, end_layout, Group, brief=False,
                        next_button_text=""):
        # создать кнопку отмена
        main_frame = self._parent.MainFrameWgt
        self.cancel_button = qt.QPushButton(self)
        if main_frame.has_errors:
            self.cancel_button.setText(_('Close'))
        else:
            self.cancel_button.setText(_('Cancel'))

        self.cancel_button.clicked.connect(self.button_disabled)
        
        self.cancel_button.clicked.connect(self.clear_method_cache)
        method_name = main_frame.method_name
        self.cancel_button.clicked.connect(
            lambda:main_frame.clear_cache_info(method_name))

        self.cancel_button.setMinimumWidth(62)
        self.cancel_button.setFixedHeight(dpivalue(32))
        if self.button_widget:
            end_layout.addWidget(self.cancel_button)

        if main_frame.has_errors:
            self.cancel_button.setShortcut(
                qt.QKeySequence(qt.Qt.Key_Return))
            self.cancel_button.setShortcut(
                qt.QKeySequence(qt.Qt.Key_Enter))
            self.default_button = self.cancel_button
        else:
            self.cancel_button.setShortcut(
                qt.QKeySequence(qt.Qt.Key_Escape))


    def add_prev_button(self, end_layout, Group, brief=False,
                        next_button_text=""):
        # создать кнопку предыдущий
        main_frame = self._parent.MainFrameWgt
        if (self.ClientObj.param_objects[main_frame.method_name]['step'] != 0
            and main_frame.mutable):
            debug(10, "CREATE PREV BUTTON")
            self.prev_button = qt.QPushButton(self)
            self.prev_button.setText(Group.prevlabel or _('Previous'))

            self.prev_button.clicked.connect(self.button_disabled)
            self.prev_button.clicked.connect(main_frame.button_call_view(-1))
            #            self.prev_button.clicked.connect(self.button_enabled)
            self.prev_button.setMinimumWidth(62)
            self.prev_button.setFixedHeight(dpivalue(32))
            if self.button_widget:
                end_layout.addWidget(self.prev_button)

    def add_next_button(self, end_layout, Group, brief=False,
                            next_button_text=""):
        # если текущая страница - brief
        # если это последний шаг, но метод без brief
        main_frame = self._parent.MainFrameWgt
        if (brief or main_frame.view.groups.GroupField[-1].last and
            not main_frame.hasBrief()):
            debug(10, "CREATE PERFORM BUTTON")
            self.next_button = qt.QPushButton(self)
            if next_button_text and brief:
                self.next_button.setText(next_button_text)
            else:
                self.next_button.setText(Group.nextlabel or _("Ok"))

            self.next_button.clicked.connect(self.button_disabled)
            if not brief:
                self.next_button.clicked.connect(
                    main_frame.collect_object())
            self.next_button.clicked.connect(main_frame.calling(False))
            if self.button_widget:
                end_layout.addWidget(self.next_button)
        else:
            debug(10, "CREATE NEXT BUTTON")
            self.next_button = qt.QPushButton(self)
            self.next_button.setText(Group.nextlabel or _("Next"))

            self.next_button.clicked.connect(self.button_disabled)
            if not brief:
                self.next_button.clicked.connect(
                    main_frame.collect_object())
            self.next_button.clicked.connect(main_frame.calling(True))
            self.next_button.clicked.connect(main_frame.button_call_view(+1))
            if self.button_widget:
                end_layout.addWidget(self.next_button)

        self.next_button.setMinimumWidth(64)
        self.next_button.setFixedHeight(dpivalue(32))
        self.next_button.setShortcut(qt.QKeySequence(qt.Qt.Key_Return))
        self.next_button.setShortcut(qt.QKeySequence(qt.Qt.Key_Enter))
        self.default_button = self.next_button

    def del_button(self):
        if self.button_widget:
            self.hlayout.removeWidget(self.button_widget)
            self.button_widget.close()
            # self.button_widget = None
        if self.prev_button:
            self.prev_button.close()
            # self.prev_button = None
        if self.cancel_button:
            self.cancel_button.close()
            # self.cancel_button = None
        if self.next_button:
            self.next_button.close()
            # self.next_button = None
        if self.customs:
            for but in self.customs:
                but.close()
                # self.customs = None
        if self.default_button:
            pass
            # self.default_button = None

    def pre_add_button(self):
        # self.del_button()
        # add 1 (or 2) button ok (next) [and previous]
        self.button_widget = qt.QWidget(self)
        end_layout = qt.QHBoxLayout(self.button_widget)
        end_layout.setContentsMargins(0, 0, 0, 0)
        end_layout.setSpacing(0)
        end_layout.addItem(qt.QSpacerItem(0, 0, \
                                             qt.QSizePolicy.Expanding,
                                             qt.QSizePolicy.Maximum))
        return end_layout

    def add_clear_cache_button(self, pid=None):
        end_layout = self.pre_add_button()
        self.clear_proc_cache_button = qt.QPushButton(_('Close'), self)
        self.default_button = self.clear_proc_cache_button
        self.ClientObj._parent.user_changed_flag = False
        if pid:
            self.pid = pid
            self.clear_proc_cache_button.clicked.connect(self.clear_pid_cache)
        else:
            self.clear_proc_cache_button.clicked.connect(self._parent.back)
        self.clear_proc_cache_button.setMinimumWidth(64)
        self.clear_proc_cache_button.setFixedHeight(dpivalue(32))
        end_layout.addWidget(self.clear_proc_cache_button)
        self.hlayout.addWidget(self.button_widget)

    def clear_pid_cache(self):
        # self.button_disabled()
        self.clear_proc_cache_button.setDisabled(True)
        sid = int(self.ClientObj.sid)
        res = self.ClientObj.client.service.clear_pid_cache(sid, self.pid)
        if (hasattr(self._parent.ClientObj, "sys_update_pid") and
                    str(self.pid) == str(
                    self._parent.ClientObj._parent.sys_update_pid)):
            self._parent.ClientObj._parent.sys_update_pid = None
        if res:
            _print(_('Error closing the process'))

        from .ConnectionTabs import SelectedMethodWgt

        if type(self.window()) == SelectedMethodWgt:
            self.window().close()
        else:
            # self.del_button()
            self.hide()
            self._parent.back()

    def clear_method_cache(self):
        self.button_disabled()
        sid = int(self.ClientObj.sid)

        if hasattr(self._parent.MainFrameWgt, 'method_name'):
            method = self._parent.MainFrameWgt.method_name
            try:
                res = self.ClientObj.client.service.clear_method_cache \
                    (sid, method)
                lerror = self.ClientObj.param_objects[method]['error']
                if(lerror):
                    while len(lerror) > 0:
                        lerror.pop()
            except Exception as e:
                print(e)
        from .ConnectionTabs import SelectedMethodWgt

        if type(self.window()) == SelectedMethodWgt:
            self.window().close()
        else:
            # self.del_button()
            self.hide()
            self._parent.back()

    def button_disabled(self):

        # if self.next_button:
        #     self.next_button.setDisabled(True)
        # if self.prev_button:
        #     self.prev_button.setDisabled(True)
        # if self.cancel_button:
        #     self.cancel_button.setDisabled(True)
        # if self.clear_proc_cache_button:
        #     self.clear_proc_cache_button.setDisabled(True)
        # if self.customs:
        #     for but in self.customs:
        #         but.setDisabled(True)
        self.ClientObj.app.processEvents()

    def button_enabled(self):
        # if self.next_button:
        #     self.next_button.setEnabled(True)
        # if self.prev_button:
        #     self.prev_button.setEnabled(True)
        # if self.cancel_button:
        #     self.cancel_button.setEnabled(True)
        # if self.clear_proc_cache_button:
        #     self.clear_proc_cache_button.setEnabled(True)
        # if self.customs:
        #     for but in self.customs:
        #         but.setEnabled(True)
        self.ClientObj.app.processEvents()

    def keyPressEvent(self, e):
        if e.key() == qt.Qt.Key_Return:
            if self.default_button:
                self.default_button.click()
        elif e.key() == qt.Qt.Key_Escape:
            if self.cancel_button:
                self.cancel_button.click()
        else:
            qt.QWidget.keyPressEvent(self, e)
