#!/usr/bin/python
# coding=utf-8
from PyQt4.QtCore import SIGNAL,Qt ,pyqtSlot, QString, SLOT,QTimer, QEvent, QPoint
from PyQt4.QtGui import QWidget, QPushButton

from ui_qss.settingQss import SettingQss
from centerSet import CenterSet
from netWokdSet import NetWokdSet
from screenResolutionSet import ScreenResolutionSet
from autoStartDesktopSet import AutoStartDesktopSet
from LogUpLoad import LogUpLoad
from logger.logrecord import LogRecord
from threading import Thread
from common.info_dialog import InfoDialog
from WaitingDialog import WaitingDialog
from common import common_run
import os

class SettingDlg(SettingQss):
    isApply=False
    def __init__(self,vmInfoList=None, mode=None,parent = None):
        super(SettingDlg, self).__init__(parent)
        self.mousePressed = False
        self.__init_class_setting(vmInfoList, mode)
        self.Waiting=WaitingDialog()
        self.waiteTimer=QTimer()
        self.__logupTimeout=5000
        self.__setting_band_signalslot()

        self.isOKClicked=False
        self.connect(self.__netWorkdSet,SIGNAL('networkFinishedSingnal'),self.__onNetworkFinished)
        self.update_current_button_style()

    def exec_(self):
        SettingDlg.isApply=False
        super(SettingDlg,self).exec_()

    def __del__(self):
        del self.__centerSet
        del self.__netWorkdSet
        del self.__ScreenResolutionSet
        del self.__autoStartDesktopSet

    def __init_class_setting(self, vmInfoList=None, mode=None):
        self.__centerSet = CenterSet()
        self.__netWorkdSet = NetWokdSet()
        self.__ScreenResolutionSet = ScreenResolutionSet()
        self.__autoStartDesktopSet = AutoStartDesktopSet(vmInfoList)
        self.gridLayout_centerset.addWidget(self.__centerSet)
        self.gridLayout_networkdset.addWidget(self.__netWorkdSet)
        self.gridLayout_screenresolutionset.addWidget(self.__ScreenResolutionSet)
        self.gridLayout_autostartdesktopdset.addWidget(self.__autoStartDesktopSet)
        self.stackedWidget.setCurrentIndex(0)

        if mode == "winlogin":  # 如果是登录界面
            self.autoStartDesktopSetting.setEnabled(False)
        else:
            self.centersetting.setEnabled(True)
            self.networkseting.setEnabled(True)
            self.__centerSet.setEnabled(True)
            # self.__centerSet.setdisable()
            self.__netWorkdSet.setEnabled(True)
            self.__layout_band_personsetting()

    def __for_btncancel_clicked(self):
        try:
            self.__autoStartDesktopSet.set_init_auto_desktop_func()
            if common_run.getCurScreenResolution() == common_run.CURRENT_SCREENRES:
                self.close()
                return
            self.__ScreenResolutionSet.set_pre_screen_resolution()
        except Exception as e:
            LogRecord.instance().logger.info(str(e.message))
        self.close()

    def __setting_band_signalslot(self):
        self.connect(self.btn_cancle, SIGNAL("clicked()"), self.__for_btncancel_clicked)
        self.connect(self.btn_close, SIGNAL("clicked()"), self.close)
        self.connect(self.btn_ok, SIGNAL("clicked()"), self.__btn_ok_slot)  # 确定
        self.connect(self.btn_yes, SIGNAL("clicked()"), self.__btn_yes_slot)  # 应用

        self.connect(self.centersetting, SIGNAL("clicked()"), self.__layout_band_centerset)
        self.connect(self.networkseting, SIGNAL("clicked()"), self.__layout_band_networkset)
        self.connect(self.screenResolutionSetting, SIGNAL("clicked()"), self.__layout_band_personsetting)
        self.connect(self.autoStartDesktopSetting, SIGNAL("clicked()"), self.__layout_band_autoStartDesktopSetting)

        # add by pbc on 2016.05.25 for log mode connect -top
        self.connect(self.__ScreenResolutionSet, SIGNAL("screen_change"), self.update_screen_fordesktop)
        self.connect(self._LogoutQss.btn_up_log, SIGNAL('clicked()'), self, SLOT('__btn_upload_log()'))
        self.connect(self.pushButton_log,SIGNAL("clicked()"),self,SLOT("__layout_band_logmode()"))
        #add by pbc on 2016.05.25 for log mode connect -end


        self.connect(self,SIGNAL("upload_finished"),self.__upload_finished)
        self.connect(self.waiteTimer,SIGNAL("timeout()"),self,SLOT("hideWaiting()"))


    # add by pbc for update screenR-top
    def update_screen_fordesktop(self):
        import time
        time.sleep(1)
        from common import init_run
        init_run.init_screen_with()
        self.update_screen_show()
        self.__centerSet.update_screen_show()
        self.__netWorkdSet.update_screen_show()
        self.__ScreenResolutionSet.update_screen_show()
        self.__autoStartDesktopSet.update_screen_show()
        self.emit(SIGNAL("screen_change"))
    # add by pbc for update screenR-end

    @pyqtSlot()
    def __btn_upload_log(self):
        """
        上传日志
        :return:
        """
        self.waiteTimer.start(self.__logupTimeout)
        self.Waiting.showMsg(u" 正在上传日志 ... ")
        self.Waiting.show()
        uploadTh=Thread(target=self.__upload_log)
        uploadTh.setDaemon(True)
        uploadTh.start()

    def __upload_log(self):
        """
        上传日志
        :return:
        """
        self._LogoutQss.btn_up_log.setEnabled(False)
        uplog = LogUpLoad()
        try:
            if not uplog.startUpload(True):
                LogRecord.instance().logger.warn("上传日志文件失败！")
                self.emit(SIGNAL('upload_finished'),u' 上传日志文件失败！ ')
            else:
                self.emit(SIGNAL('upload_finished'),u' 上传日志成功，日志文件编号：%s '%uplog.logNo)
        except Exception,err:
            LogRecord.instance().logger.exception("上传日志文件异常！")
            self.emit(SIGNAL('upload_finished'),u' 上传日志文件失败！ ')
        self._LogoutQss.btn_up_log.setEnabled(True)

    def __upload_finished(self,msg):
        self.hideWaiting()
        InfoDialog.instance().Information(u'提示',msg)

    @pyqtSlot()
    def hideWaiting(self):
        self.waiteTimer.stop()
        self.Waiting.close()

    def __onNetworkFinished(self,isTimeout):
        LogRecord.instance().logger.debug('__onNetworkFinished')
        if isTimeout:
            self.__enableBtn(True)
            return
        if self.isOKClicked:
            self.isOKClicked=False
            try:
                LogRecord.instance().logger.debug('__onNetworkFinished')
            finally:
                self.__enableBtn(True)
            self.close()
        else:
            self.__enableBtn(True)

    def __btn_ok_slot(self): ## 确定
        try:
            self.__autoStartDesktopSet.set_auto_desktop_func()
            # self.__ScreenResolutionSet.setScreenResolution()  # 更新屏幕分辨率
            retu = self.__netWorkdSet.setNetWork()
            if retu == False:
                return
            if (str(self.__centerSet.lineEdit_ip.text()).strip() != ''):
                retu = self.__centerSet.add_platform()
                if retu == False:
                    return
            self.__ScreenResolutionSet.setScreenResolution()  # 更新屏幕分辨率
        except Exception as  e:
            LogRecord.instance().logger.info(str(e.message))
            self.close()
        self.__enableBtn(False)
        self.isOKClicked=True
        self.__enableBtn(True)
        # if not self.__netWorkdSet.setNetWork():  # 更新网络设置，使之生效
        #     self.__enableBtn(True)
        #     self.close()
        #     return
        self.close()


    def __enableBtn(self,able):
        if not isinstance(able,bool):
            LogRecord.instance().logger.warn("设置按钮可用性错误：%s"%( str(type(able)) ) )
            return
        self.btn_yes.setEnabled(able)
        self.btn_ok.setEnabled(able)
        self.btn_cancle.setEnabled(able)
        self.btn_close.setEnabled(able)

        # self.centersetting.setEnabled(able)
        # self.networkseting.setEnabled(able)
        # self.screenResolutionSetting.setEnabled(able)
        # self.autoStartDesktopSetting.setEnabled(able)
        # self.pushButton_log.setEnabled(able)

    def __btn_yes_slot(self):  ## 应用
        try:
            self.__enableBtn(False)
            curIndex = self.stackedWidget.currentIndex()
            if curIndex == 0:  # 平台设置  应用
                if (str(self.__centerSet.lineEdit_ip.text()).strip() != ''):
                    self.__centerSet.add_platform()
            elif curIndex == 1:  # 网络设置应用
                self.__netWorkdSet.setNetWork()  # 更新网络设置，使之生效
            elif curIndex == 2:  # 分辨率设置应用
                SettingDlg.isApply=True
                self.__ScreenResolutionSet.setScreenResolution()  # 更新屏幕分辨率
            elif curIndex == 3:  # 自启动桌面
                self.__autoStartDesktopSet.set_auto_desktop_func()
        except Exception as e:
            print "点击 设置-应用按钮 : ", e.message
        finally:
            self.__enableBtn(True)

    @pyqtSlot()
    def __layout_band_centerset(self):
        self.stackedWidget.setCurrentIndex(0)
        self.update_current_button_style()

    @pyqtSlot()
    def __layout_band_networkset(self):
        # if self.__netWorkdSet.detectNetworkState():
        #     LogRecord.instance().logger.warn("本地网络连接异常！")
        self.stackedWidget.setCurrentIndex(1)
        self.update_current_button_style()

    @pyqtSlot()
    def __layout_band_personsetting(self):
        self.stackedWidget.setCurrentIndex(2)
        self.update_current_button_style()


    @pyqtSlot()
    def __layout_band_autoStartDesktopSetting(self):
        self.stackedWidget.setCurrentIndex(3)
        self.update_current_button_style()

    @pyqtSlot()
    def __layout_band_logmode(self):
        self.stackedWidget.setCurrentIndex(4)
        self.update_current_button_style()


    def mousePressEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.currentPos = event.pos()
            self.mousePressed = True

    def mouseReleaseEvent(self, event):
        self.mousePressed = False

    def mouseMoveEvent(self, event):
        if self.mousePressed:
            self.move(self.pos() + event.pos() - self.currentPos)
        self.default = QString()


###############################
#   单元测试
##############################
if __name__ == "__main__":
    from PyQt4 import QtGui
    from os import environ

    from PyQt4.QtCore import QTextCodec

    QTextCodec.setCodecForCStrings(QTextCodec.codecForLocale())  # 支持中文

    environ["WIN_UI_IMAGES_PATH"] = "../../images"
    environ["MCOS_CONFIG_FILE"] = "./userInfoConfFile/centerset.conf"

    app = QtGui.QApplication([])
    win = SettingDlg()
    win.show()
    app.exec_()
