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

# Copyright 2012-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 PySide import QtGui, QtCore
from more import LabelWordWrap, _print


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

        # Set style
        self.setAttribute(QtCore.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 = QtGui.QHBoxLayout(self)
        self.hlayout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.hlayout.setContentsMargins(28,0,0,0)
        self.hlayout.setSpacing(0)

        self.meth_name = QtGui.QLabel('Method Name', self)
#        self.meth_name.setAlignment(QtCore.Qt.AlignLeft)
        self.meth_name.setStyleSheet("font-size: 16px;"
                                     "font: bold;"
                                     "color: white;");

#                                  "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(40)
        self.hide()

    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 hasattr (self, 'button_widget'):
            self.hlayout.removeWidget(self.button_widget)
            self.button_widget.close()
        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(QtGui.QWidget):
    def __init__(self, parent, ClientObj):
        QtGui.QWidget.__init__(self, parent)
        self._parent = parent
        self.ClientObj = ClientObj

        # Set style
        self.setAttribute(QtCore.Qt.WA_StyledBackground)
        self.setObjectName('ControlButton')
        self.setStyleSheet("QWidget#ControlButton "
#                           "{background-color: #FF0000;}")
                           "{background-color: #FFFFFF;}")

        self.main_layout = QtGui.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 = QtGui.QHBoxLayout()
        self.hlayout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.hlayout.setContentsMargins(0,0,28,0)
        self.hlayout.setSpacing(0)
        self.main_layout.addItem(QtGui.QSpacerItem( 0, 0, \
                                              QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding ))
        self.main_layout.addLayout(self.hlayout)

        #self.setLayout(self.hlayout)
        self.setFixedHeight(90)
        self.hide()
        self.confirmWgt = None
        self.break_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 hasattr (self, 'button_widget'):
            self.hlayout.removeWidget(self.button_widget)
            self.button_widget.close()
        self.hide()

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

        if self.ClientObj.param_objects[main_frame.method_name]['step'] != 0:
            self.prev_button = QtGui.QPushButton(self) 
            try:
                pass
#                self.prev_button.setIcon(QtGui.QIcon.fromTheme("go-previous"))
            finally:
                if Group.prevlabel:
                    self.prev_button.setText(Group.prevlabel)
                else:
                    self.prev_button.setText(_('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(32)
            if hasattr (self, 'button_widget'):
                end_layout.addWidget(self.prev_button)
#            self.grid.addWidget(self.prev_button, x, y)
        else:
            self.prev_button = QtGui.QPushButton(self)
            self.prev_button.setText(_('Cancel').decode('utf-8'))

            self.prev_button.clicked.connect(self.button_disabled)
            self.prev_button.clicked.connect(self.clear_method_cache)

            self.prev_button.setMinimumWidth(62)
            self.prev_button.setFixedHeight(32)
            if hasattr (self, 'button_widget'):
                end_layout.addWidget(self.prev_button)

        if main_frame.view.groups.GroupField[-1].last and not \
                               main_frame.isBrief(self.ClientObj.param_objects\
                               [main_frame.method_name]['step']+1) or brief:
            self.next_button = QtGui.QPushButton(self)
            try:
                pass
#                ok_icon = QtGui.QIcon.fromTheme("dialog-ok-apply")
#                if ok_icon.isNull():
#                    ok_icon = ok_icon.fromTheme("go-next")
#                self.next_button.setIcon(ok_icon)
            finally:
                if Group.nextlabel:
                    self.next_button.setText(Group.nextlabel)
                else:
                    self.next_button.setText(_('Ok'))
                if next_button_text and brief:
                    self.next_button.setText(next_button_text)
            self.next_button.clicked.connect(self.button_disabled)
            if not brief:
                self.next_button.clicked.connect(main_frame.collect_object \
                                                (False))
            self.next_button.clicked.connect(main_frame.calling(False))
            if hasattr (self, 'button_widget'):
                end_layout.addWidget(self.next_button)
        else:
            self.next_button = QtGui.QPushButton(self)
            try:
                pass
#                self.next_button.setIcon(QtGui.QIcon.fromTheme("go-next"))
            finally:
                if Group.nextlabel:
                    self.next_button.setText(Group.nextlabel)
                else:
                    self.next_button.setText(_('Next'))

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

        self.next_button.setMinimumWidth(64)
        self.next_button.setFixedHeight(32)
        self.next_button.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Return))
        self.next_button.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Enter))
#        self.next_button.setMaximumHeight(38)

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

    def del_button(self):
        if hasattr (self, 'button_widget'):
            self.hlayout.removeWidget(self.button_widget)
            self.button_widget.close()
        if hasattr (self, 'prev_button'):
            self.prev_button.close()
        if hasattr (self, 'next_button'):
            self.next_button.close()

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

    def add_clear_cache_button(self, pid = None):
        end_layout = self.pre_add_button()
        self.clear_proc_cache_button = QtGui.QPushButton(_('Close'), self)
        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(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 calculate.consolegui.application.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']
                while len(lerror)>0:
                    lerror.pop()
            except Exception as e:
                print e
        from calculate.consolegui.application.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 hasattr(self, 'next_button'):
            self.next_button.setDisabled(True)
        if hasattr(self, 'prev_button'):
            self.prev_button.setDisabled(True)
        if hasattr(self, 'clear_proc_cache_button'):
            self.clear_proc_cache_button.setDisabled(True)
        self.ClientObj.app.processEvents()

    def button_enabled(self):
        if hasattr(self, 'next_button'):
            self.next_button.setEnabled(True)
        if hasattr(self, 'prev_button'):
            self.prev_button.setEnabled(True)
        if hasattr(self, 'clear_proc_cache_button'):
            self.clear_proc_cache_button.setEnabled(True)
        self.ClientObj.app.processEvents()

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Return:
            if hasattr (self, 'next_button'):
                self.next_button.click()
        else:
            QtGui.QWidget.keyPressEvent(self, e)
