# coding=utf-8


from ui_qss.centerSetQss import CenterSetQss
from PyQt4.QtCore import SIGNAL, Qt, QRegExp, QTimer, QEvent, QPoint, QEventLoop
import PyQt4
from PyQt4.QtGui import QTableWidgetItem, QRegExpValidator, QWidget
from messageDialog import MessageDialog
from common.info_dialog import InfoDialog
import subprocess
from logger.logrecord import LogRecord
from userInfoConfFile.userInfoConf import UserInfoConfFile
import re

from threading import Thread, Event


#  平台设置窗口
class CenterSet(CenterSetQss):
    def __init__(self):
        super(CenterSet, self).__init__()

        # 设置格式判断

        # reg = QRegExp('^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-4])$')
        reg=QRegExp('^[0-9\.]{0,15}$')
        validator = QRegExpValidator(reg)
        self.lineEdit_ip.setValidator(validator)

        # validator2 = QIntValidator(0,65535)  # 端口范围 0-65535

        # 端口 输入 1-65535
        # reg2 = QRegExp(
        #     '^([1-9] | [1-9]\\d\\d\\d | [1-5]\\d\\d\\d\\d |6[0-4]\\d\\d\\d |65[0-4]\\d\\d |655[0-2]\\d|6553[0-5])$')
        # 限制 端口 输入  (1-65535)
        reg2 = QRegExp("^([1-9]\\d{0,3}|[1-5]\\d{4}|6[0-4]\\d{3}|65[0-4]\\d\\d|655[0-2]\\d|6553[0-5])$")
        validator2 = QRegExpValidator(reg2)
        self.lineEdit_port.setValidator(validator2)

        self.lineEdit_port.setPlaceholderText(str("8080"))

        self.__band_signal_slot()

        self.conf = UserInfoConfFile()  # 实例化UserInfoConfFile对象
        centerList = self.conf.getCenterList()
        for i in range(len(centerList)):
            print "ip :", centerList[i]["centerIp"]
            print "name :", centerList[i]["centerName"]
            self.__addCentInfoToTableWidget(centerList[i]["centerIp"],
                                            centerList[i]["centerName"])  # 添加平台 到 TableWidget

        self.lineEdit_ip.setContextMenuPolicy(Qt.NoContextMenu)
        self.lineEdit_port.setContextMenuPolicy(Qt.NoContextMenu)

    def __del__(self):
        del self.conf  # 释放内存
        print "--CenterSet del--"

    def __band_signal_slot(self):
        self.connect(self.btn_add, SIGNAL("clicked()"), self.__center_add_slot)  # 添加
        self.connect(self.btn_delete, SIGNAL("clicked()"), self.__center_delete_slot)
    def setdisable(self):
        from PyQt4.QtCore import QString
        from common import common_run
        import os
        __font_size = str(int(common_run.get_width(11.0)))
        borderImagesPath =  os.getenv('WIN_UI_IMAGES_PATH')    # 读取环境变量
        self.btn_add.setStyleSheet(
             QString("QPushButton{font:63 "+__font_size+"pt;}"
                     "QPushButton:disabled{color: rgba(0,0,0,100);font:63 "+__font_size+"pt;border-image: url(%1/settingWindow/btn_backgound1.png);border: 2px;}").arg(str(borderImagesPath))
        )
        self.btn_delete.setStyleSheet(
             QString("QPushButton{font:63 "+__font_size+"pt;}"
                     "QPushButton:disabled{color: rgba(0,0,0,100);font:63 "+__font_size+"pt;border-image: url(%1/settingWindow/btn_backgound1.png);border: 2px;}").arg(str(borderImagesPath))
        )
        self.setDisabled(True)



    # 删除平台
    @PyQt4.QtCore.pyqtSlot()
    def __center_delete_slot(self):  # 删除


        # InfoDialog.instance().Information(u'实例化',u'更改密码对象窗口')#仅仅 提示信息

        # if 'yes' == InfoDialog.instance().MessageBox(u'实例化', u'更改密码对象窗口'): # 提示信息,选择
        #     pass
        # else:
        #     pass

        # retu = InfoDialog.instance().MessageBox(u'实例化',u'更改密码对象窗口')# choose yes or no
        # InfoDialog.instance().InformationTimer()# timer waiting ....

        # 请选择要删除的平台
        if self.tableWidget.currentRow() == -1:
            InfoDialog.instance().Information(u'提示', u'请选择要删除的平台')  # 仅仅 提示信息
            return None


        print "current index  : ", self.tableWidget.currentRow()

        if self.tableWidget.rowCount() > 0:
            centerIp = str(self.tableWidget.item(self.tableWidget.currentRow(), 1).text())
            centerName = str(self.tableWidget.item(self.tableWidget.currentRow(), 0).text())

            res = InfoDialog.instance().MessageBox(u'提示',u'你确定要删除平台：'+centerName+'（'+centerIp+'）吗？')
            if res == 'no':
                return
            elif res == 'yes':

                # print centerIp

                self.conf.deleteCenter(centerIp)  # 从conf文件删除平台
                self.tableWidget.removeRow(self.tableWidget.currentRow())  # 删除行

                # if self.tableWidget.rowCount() > 0:
                #     centerIp = str(self.tableWidget.item(self.tableWidget.rowCount() - 1,1).text())
                #     #print centerIp
                #
                #     self.conf.deleteCenter(centerIp)                             # 从conf文件删除平台
                #     self.tableWidget.removeRow(self.tableWidget.rowCount() - 1)  # 删除行

    def isIP(self,ip):
        """
        验证IP是否是有效IP
        :param ip:
        :return:
        """
        ipReg=re.compile('^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-4])$')
        if not re.match(ipReg,ip):
            return False
        return True

    #add by wangshigang for add platform
    def add_platform(self):
        self.btn_add.setEnabled(False)
        try:
            ip = str(self.lineEdit_ip.text())  # 输入检查
            port = str(self.lineEdit_port.text())  # 输入检查

            if port == "":
                port = "8080"

            if ip == "":
                InfoDialog.instance().Information(u'提示',u'请输入平台ip地址')#仅仅 提示信息
                return False

            if not self.isIP(ip):
                InfoDialog.instance().Information(u'提示',u'输入的平台IP格式错误，请输入正确的平台IP！')#仅仅 提示信息
                return False

            centerIp = ip + ":" + port

            if self.conf.has_center(centerIp):
                InfoDialog.instance().Information(u'提示', centerIp + " 已经存在")#仅仅 提示信息
                # MessageDialog(centerIp + " 已经存在").exec_()
                return False
            #-----------------------------
            from sendCmd.validate.getCenterName import CenterName
            __eventLop = QEventLoop()
            started_evt = Event()
            result = {
               "status":False,
                "info" :""
            }
            #=========== 子线程==============
            def func(centerIp):
                try:
                    started_evt.set()
                    __centerName = CenterName(centerIp)
                    res = __centerName.getCenterName()
                    result["status"] = res[0]
                    result["info"] = res[1]
                finally:
                    while not __eventLop.isRunning():    # 等待父线程，执行到 loginEventLop.exec_()
                        pass
                    __eventLop.quit()
            #=============================
            __thread = Thread(target=func,args=(centerIp,))  # 初始化接收线程
            __thread.setDaemon(True)    # 设置 Daemon
            __thread.start()

            started_evt.wait()   # 等待 子线程 运行
            __eventLop.exec_()    # 进入qt事件循环  防止界面卡顿，事件
            #-----------------

            if result["status"] == False:
                # InfoDialog.instance().Information(u'提示',centerIp + u"平台不存在")#仅仅 提示信息
                InfoDialog.instance().Information(u'提示',str(result["info"]))#仅仅 提示信息
                return False
            else:
                centerName = result["info"]

            self.conf.addCenter(centerIp, centerName)  # 添加平台 到 conf文件
            self.__addCentInfoToTableWidget(centerIp, centerName)  # 添加平台 到 TableWidget
            self.lineEdit_ip.setText("")  # 清空 lineEdit输入  平台ip
            self.lineEdit_port.setText("")  # 清空 lineEdit输入  平台ip
            return True

        except Exception:
            InfoDialog.instance().Information(u'提示',u'添加中心异常！')#仅仅 提示信息
            return False
        finally:
            self.btn_add.setEnabled(True)

    # 添 加 平台
    @PyQt4.QtCore.pyqtSlot()
    def __center_add_slot(self):  # 添加平台
        if not self.add_platform():
            LogRecord.instance().logger.info('添加新平台失败！')


    # def __detectNetwork(self):
    #     try:
    #         nm_tool_process = subprocess.Popen("nm-tool", stdout=subprocess.PIPE)
    #         nm_tool_out = nm_tool_process.stdout.read()
    #         tool_outs = nm_tool_out.splitlines()
    #         try:
    #             for line in tool_outs:
    #                 if line.find('State:')>=0:
    #                     if line.find('disconnected')>=0:
    #                         return False
    #                     elif line.find('connected')>=0:
    #                         return True
    #         except Exception, err:
    #             LogRecord.instance().logger.exception("检测本地网络连接失败！")
    #     except Exception,err:
    #         LogRecord.instance().logger.exception("检测本地网络连接,执行命令nm-tool失败！")
    #     return False


    def __addCentInfoToTableWidget(self, centerIp, centerName, centerDomainName=""):

        self.tableWidget.insertRow(self.tableWidget.rowCount())  # 插入行
        # ---------
        ipItem = QTableWidgetItem(centerIp)  #
        centerNameItem = QTableWidgetItem(centerName)  #
        centerDomainNameItem = QTableWidgetItem(centerDomainName)  #

        ipItem.setTextAlignment(Qt.AlignCenter)
        centerNameItem.setTextAlignment(Qt.AlignCenter)
        centerDomainNameItem.setTextAlignment(Qt.AlignCenter)
        # ---------
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 0, centerNameItem)  # 添加 平台名
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 1, ipItem)  # 添加 平台ip
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 2, centerDomainNameItem)  # 添加 平台ip

    # 返回 平台配置信息列表
    def getCeterInfoList(self):
        print "---------- test ------------"
        centInfo = {"centerName": "", "centerIp": "", "centerDomainName": ""}
        centerInfoList = []
        for n in range(self.tableWidget.rowCount()):
            centInfo["centerName"] = str(self.tableWidget.item(n, 0).text())
            centInfo["centerIp"] = str(self.tableWidget.item(n, 1).text())
            centInfo["centerDomainName"] = str(self.tableWidget.item(n, 2).text())
            centerInfoList.append(centInfo)
        return centerInfoList

    def add_center_fun(self):
        pass

    def check_center_name(self, center_name):
        pass

    def update_center_info(self):
        pass

    def keyPressEvent(self,event):
        if (event.key() == Qt.Key_Enter) or (event.key() == Qt.Key_Return):
            if (self.lineEdit_ip.hasFocus() or
                    self.lineEdit_port.hasFocus()):
                self.__center_add_slot()


#############################
## 测试用例
###########################
if __name__ == "__main__":
    import sys
    from os import getenv , environ

    reload(sys)
    sys.setdefaultencoding('utf-8')
    from PyQt4 import QtGui
    from PyQt4.QtCore import QTextCodec

    QTextCodec.setCodecForCStrings(QTextCodec.codecForLocale())  # 支持中文
    app = QtGui.QApplication([])

    if getenv('LOG_STDOUT') == None:
        environ["LOG_STDOUT"] = "stdout"  #

    environ["WIN_UI_IMAGES_PATH"] = "../../images"
    environ["MCOS_CONFIG_FILE"] = "./userInfoConfFile/centerset.conf"
    logindlg = CenterSet()
    logindlg.show()

    app.exec_()
