#coding:utf-8
from PyQt4 import QtCore
from PyQt4 import QtGui
from threading import Thread
import time
import os
import re
import subprocess
from logger.logrecord import LogRecord

from userInfoConfFile.userInfoConf import UserInfoConfFile
from modifyNetWork import modifyNetWork
from sendCmd.validate.getCenterName import CenterName
from common import network_set_func

class ForeSetting(QtGui.QDialog):
    """
    登录前网络及平台设置
    """
    def __init__(self,parent=None):
        QtGui.QDialog.__init__(self,parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setModal(True)
        self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowStaysOnTopHint)
        self.__imagePath=os.getenv('WIN_UI_IMAGES_PATH')

        self.__networkDic={}
        self.__networkDic['address'] = ''
        self.__networkDic['netmask'] = ''
        self.__networkDic['gateway'] = ''
        self.__networkDic['nameserver'] = ''
        self.__networkDic['nameserver1'] = ''
        self.__networkDic['isAutoIP']='True'
        self.__networkDic['isAutoDNS']='True'
        self.conf=UserInfoConfFile()

        # ipReg=QtCore.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])$')
        ipReg=QtCore.QRegExp('^[0-9\.]{0,15}$')
        self.ipValidator = QtGui.QRegExpValidator(ipReg)
        self.ipMask='000.000.000.000'
        portReg=QtCore.QRegExp('^[1-9][0-9]{0,4}$')
        self.portValidator=QtGui.QRegExpValidator(portReg)
        self.msgTimer=QtCore.QTimer()
        self.refresh()

        self.connect(self.autoIP, QtCore.SIGNAL('clicked()'), self.onAutoIP)
        self.connect(self.staticIP, QtCore.SIGNAL('clicked()'), self.onStaticIP)
        self.connect(self.autoDNS,QtCore.SIGNAL('clicked()'),self.onAutoDNS)
        self.connect(self.staticDNS,QtCore.SIGNAL('clicked()'),self.onStaticDNS)
        self.connect(self.centerNameComboBox,QtCore.SIGNAL('currentIndexChanged(int)'),self,QtCore.SLOT('onSelectedCenter(int)'))
        self.connect(self.msgTimer,QtCore.SIGNAL('timeout()'),self,QtCore.SLOT('onMsgTimeout()'))
        self.connect(self.confirmBtn,QtCore.SIGNAL('clicked()'),self,QtCore.SLOT('onConfirm()'))
        self.connect(self,QtCore.SIGNAL('onSetNetWorkSignal()'),self,QtCore.SLOT('onSetNetwork()'))
        self.connect(self,QtCore.SIGNAL('onSetCenterSignal()'),self,QtCore.SLOT('onSetCenter()'))
        self.connect(self,QtCore.SIGNAL('onWaitNetWorkSignal()'),self,QtCore.SLOT('onWaitNetWork()'))


    def refresh(self):
        """
        设置界面布局
        :return:
        """
        desktop=QtGui.QApplication.desktop()
        self.__width=desktop.width()
        self.__height=desktop.height()
        self.__leftBlank=self.__width//40
        self.__topBlank=self.__height//10
        self.__ipGroupWidth=(self.__width*9)//20
        self.__ipGroupHeight=(self.__height*6)//25
        self.__ipWidth=self.__width//5
        self.__ipHeight=self.__height//33
        self.__ipLeftBlank=self.__ipGroupWidth//3
        self.__ipTopBlank=self.__ipGroupHeight//8
        self.__radioHeight=self.__ipHeight*3//4
        self.__ipMiddleBlank=self.__ipGroupWidth//10
        self.__centerWidth=self.__ipGroupWidth-((self.__ipGroupWidth-self.__ipLeftBlank-self.__ipWidth)-(self.__width//5-self.__width//7))
        self.__centerHeight=self.__ipGroupHeight

        self.__labelColor="color:rgba(255,255,255,255);"
        self.__disableColor="color:rgba(0,0,0,100);"
        self.__editBackground="QLineEdit{border-image:url(%s/input.png);background:transparent;color:rgba(100,100,100,200);}"%self.__imagePath
        self.__radioSize="width:%dpx;height:%dpx;"%(self.__ipHeight//2,self.__ipHeight//2)
        self.__radioStryle=("QRadioButton::indicator::unchecked {image: url(%s/radio1.png);%s}"%(self.__imagePath,self.__radioSize)+
                                  "QRadioButton::indicator::checked {image: url(%s/radio2.png);%s}"%(self.__imagePath,self.__radioSize)+
                                  "QRadioButton{%s}"%self.__labelColor+
                                  "QRadioButton:disabled{%s}"%self.__disableColor)

        # self.setStyleSheet("QDialog{background-color:rgb(9,26,35);}")
        self.setStyleSheet("QDialog{border-image:url(%s/winVirturlList/background_down.png);}"%self.__imagePath)

        self.confirmBtn=QtGui.QPushButton(self)
        self.confirmBtn.setGeometry(self.__width-self.__width//7-(self.__ipGroupWidth-self.__ipLeftBlank-self.__ipWidth),
                                    self.__height-self.__height//10,
                                    self.__width//7,
                                    self.__height//25)
        # self.confirmBtn.setText('确认'.decode('utf-8'))self.confirmBtn.setFlat(True)
        self.confirmBtn.setFocusPolicy(QtCore.Qt.NoFocus)
        self.confirmBtn.setStyleSheet("QPushButton{border-image:url(%s/loginWindow/confirm1.png)}"%self.__imagePath+
                           "QPushButton:hover{border-image:url(%s/loginWindow/confirm2.png)}"%self.__imagePath+
                           "QPushButton:pressed{border-image:url(%s/loginWindow/confirm3.png)}"%self.__imagePath)

        groupFont=QtGui.QFont()
        groupFont.setPointSize(14)
        # groupFont.setBold(True)
        contentFont=QtGui.QFont()
        contentFont.setPointSize(10)
        radioFont=QtGui.QFont()
        radioFont.setPointSize(11)

        #IP设置
        self.ipGroup=QtGui.QGroupBox(self)
        # self.ipGroup.setTitle('IP设置:'.decode('utf-8'))
        self.ipGroup.setFont(groupFont)
        self.ipGroup.setStyleSheet("QGroupBox{border-image:url(%s/IPsetting.png);color:rgba(255,255,255,200);border:0px;}"%self.__imagePath)
        self.ipGroup.setGeometry(self.__leftBlank,self.__topBlank,self.__ipGroupWidth,self.__ipGroupHeight)
        ipTop=self.__ipTopBlank
        self.autoIP=QtGui.QRadioButton(self.ipGroup)
        self.autoIP.setFocusPolicy(QtCore.Qt.NoFocus)
        self.autoIP.setText('自动获取IP'.decode('utf-8'))
        self.autoIP.setGeometry(self.__ipWidth//10,ipTop,self.__ipWidth,self.__radioHeight)
        self.autoIP.setFont(radioFont)
        self.autoIP.setStyleSheet(self.__radioStryle)
        ipTop+=self.__radioHeight+self.__ipHeight//2
        self.staticIP=QtGui.QRadioButton(self.ipGroup)
        self.staticIP.setFocusPolicy(QtCore.Qt.NoFocus)
        self.staticIP.setText('静态IP'.decode('utf-8'))
        self.staticIP.setGeometry(self.__ipWidth//10,ipTop,self.__ipWidth//2,self.__radioHeight)
        self.staticIP.setFont(radioFont)
        self.staticIP.setStyleSheet(self.__radioStryle)
        ipTop+=self.__radioHeight+self.__ipHeight//2
        self.ipLabel=QtGui.QLabel(self.ipGroup)
        self.ipLabel.setText('IP地址:'.decode('utf-8'))
        self.ipLabel.setFont(contentFont)
        self.ipLabel.setGeometry(self.__ipLeftBlank//6,ipTop,self.__ipLeftBlank,self.__ipHeight)
        self.ipLabel.setStyleSheet("QLabel{%s}"%self.__labelColor)
        self.ipEdit=QtGui.QLineEdit(self.ipGroup)
        # self.ipEdit.setInputMask(self.ipMask)
        # self.ipEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.ipEdit.setValidator(self.ipValidator)
        self.ipEdit.setGeometry(self.__ipLeftBlank,ipTop,self.__ipWidth,self.__ipHeight)
        self.ipEdit.setStyleSheet(self.__editBackground)
        ipTop+=self.__ipHeight+self.__ipHeight//2
        self.subLabel=QtGui.QLabel(self.ipGroup)
        self.subLabel.setText('子网掩码：'.decode('utf-8'))
        self.subLabel.setFont(contentFont)
        self.subLabel.setGeometry(self.__ipLeftBlank//6,ipTop,self.__ipLeftBlank,self.__ipHeight)
        self.subLabel.setStyleSheet("QLabel{%s}"%self.__labelColor)
        self.subEdit=QtGui.QLineEdit(self.ipGroup)
        # self.subEdit.setInputMask(self.ipMask)
        # self.subEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.subEdit.setValidator(self.ipValidator)
        self.subEdit.setGeometry(self.__ipLeftBlank,ipTop,self.__ipWidth,self.__ipHeight)
        self.subEdit.setStyleSheet(self.__editBackground)
        ipTop+=self.__ipHeight+self.__ipHeight//2
        self.gateLabel=QtGui.QLabel(self.ipGroup)
        self.gateLabel.setText('网关：'.decode('utf-8'))
        self.gateLabel.setFont(contentFont)
        self.gateLabel.setGeometry(self.__ipLeftBlank//6,ipTop,self.__ipLeftBlank,self.__ipHeight)
        self.gateLabel.setStyleSheet("QLabel{%s}"%self.__labelColor)
        self.gateEdit=QtGui.QLineEdit(self.ipGroup)
        # self.gateEdit.setInputMask(self.ipMask)
        # self.gateEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.gateEdit.setValidator(self.ipValidator)
        self.gateEdit.setGeometry(self.__ipLeftBlank,ipTop,self.__ipWidth,self.__ipHeight)
        self.gateEdit.setStyleSheet(self.__editBackground)

        #DNS设置
        self.dnsGroup=QtGui.QGroupBox(self)
        # self.dnsGroup.setTitle('DNS设置:'.decode('utf-8'))
        self.dnsGroup.setStyleSheet("QGroupBox{border-image:url(%s/DNSsetting.png);color:rgba(255,255,255,200);border:0px;}"%self.__imagePath)
        self.dnsGroup.setGeometry(self.__leftBlank,self.__height*2//5,self.__ipGroupWidth,4*self.__ipGroupHeight//5)
        self.dnsGroup.setFont(groupFont)
        dnsTop=self.__ipTopBlank
        self.autoDNS=QtGui.QRadioButton(self.dnsGroup)
        self.autoDNS.setFocusPolicy(QtCore.Qt.NoFocus)
        self.autoDNS.setText('自动获取DNS'.decode('utf-8'))
        self.autoDNS.setGeometry(self.__ipWidth//10,dnsTop,self.__ipWidth,(self.__ipHeight))
        self.autoDNS.setFont(radioFont)
        self.autoDNS.setStyleSheet(self.__radioStryle)
        dnsTop+=self.__radioHeight+self.__ipHeight//2
        self.staticDNS=QtGui.QRadioButton(self.dnsGroup)
        self.staticDNS.setFocusPolicy(QtCore.Qt.NoFocus)
        self.staticDNS.setText('静态DNS'.decode('utf-8'))
        self.staticDNS.setGeometry(self.__ipWidth//10,dnsTop,self.__ipWidth//2,self.__ipHeight)
        self.staticDNS.setFont(radioFont)
        self.staticDNS.setStyleSheet(self.__radioStryle)
        dnsTop+=self.__radioHeight+self.__ipHeight//2
        self.dns1Label=QtGui.QLabel(self.dnsGroup)
        self.dns1Label.setText('首选DNS:'.decode('utf-8'))
        self.dns1Label.setFont(contentFont)
        self.dns1Label.setGeometry(self.__ipLeftBlank//6,dnsTop,self.__ipLeftBlank,self.__ipHeight)
        self.dns1Label.setStyleSheet("QLabel{%s}"%self.__labelColor)
        self.dns1Edit=QtGui.QLineEdit(self.dnsGroup)
        # self.dns1Edit.setInputMask(self.ipMask)
        # self.dns1Edit.setAlignment(QtCore.Qt.AlignCenter)
        self.dns1Edit.setValidator(self.ipValidator)
        self.dns1Edit.setGeometry(self.__ipLeftBlank,dnsTop,self.__ipWidth,self.__ipHeight)
        self.dns1Edit.setStyleSheet(self.__editBackground)
        dnsTop+=self.__ipHeight+self.__ipHeight//2
        self.dns2Label=QtGui.QLabel(self.dnsGroup)
        self.dns2Label.setText('备用DNS:'.decode('utf-8'))
        self.dns2Label.setFont(contentFont)
        self.dns2Label.setGeometry(self.__ipLeftBlank//6,dnsTop,self.__ipLeftBlank,self.__ipHeight)
        self.dns2Label.setStyleSheet("QLabel{%s}"%self.__labelColor)
        self.dns2Edit=QtGui.QLineEdit(self.dnsGroup)
        # self.dns2Edit.setInputMask(self.ipMask)
        # self.dns2Edit.setAlignment(QtCore.Qt.AlignCenter)
        self.dns2Edit.setValidator(self.ipValidator)
        self.dns2Edit.setGeometry(self.__ipLeftBlank,dnsTop,self.__ipWidth,self.__ipHeight)
        self.dns2Edit.setStyleSheet(self.__editBackground)

        #初始化网络设置显示
        self.getLocalNetWork()

        #配置平台服务器
        self.centerGroup=QtGui.QGroupBox(self)
        self.centerGroup.setGeometry(self.__width-self.__centerWidth-self.__leftBlank,
                         self.__topBlank,
                         self.__centerWidth,
                         self.__centerHeight)
        #centerSetting.png
        self.centerGroup.setStyleSheet("QGroupBox{border-image:url(%s/centerSetting.png);color:rgba(255,255,255,255);border:0px;}"%self.__imagePath)
        # self.centerGroup.setTitle('平台配置：'.decode('utf-8'))
        self.centerGroup.setFont(groupFont)
        # centerTop=self.__ipTopBlank
        # self.chooseCenter=QtGui.QRadioButton(self.centerGroup)
        # self.chooseCenter.setText('选择平台'.decode('utf-8'))
        # self.chooseCenter.setGeometry(self.__ipLeftBlank,centerTop,self.__ipWidth//2,self.__ipHeight)
        # self.setCenter=QtGui.QRadioButton(self.centerGroup)
        # self.setCenter.setText('设置平台'.decode('utf-8'))
        # self.setCenter.setGeometry(self.__ipLeftBlank+self.__ipWidth//2+self.__ipMiddleBlank,centerTop,self.__ipWidth//2,self.__ipHeight)
        # centerTop+=self.__ipHeight+self.__ipHeight//2
        centerTop=self.__ipTopBlank+self.__ipHeight*2+self.__ipHeight//2
        self.centerNameLabel=QtGui.QLabel(self.centerGroup)
        self.centerNameLabel.setText('平台名:'.decode('utf-8'))
        self.centerNameLabel.setFont(contentFont)
        self.centerNameLabel.setGeometry(self.__ipLeftBlank//4,centerTop,self.__ipLeftBlank,self.__ipHeight)
        self.centerNameLabel.setStyleSheet("QLabel{%s}"%self.__labelColor)
        self.centerNameBack=QtGui.QLabel(self.centerGroup)
        self.centerNameBack.setGeometry(self.__ipLeftBlank,centerTop,self.__ipWidth,self.__ipHeight)
        self.centerNameBack.setStyleSheet("QLabel{border-image:url(%s/input.png);background:transparent;}"%self.__imagePath)
        self.centerNameComboBox=QtGui.QComboBox(self.centerNameBack)
        self.centerNameComboBox.setGeometry(2,2,self.__ipWidth-4,self.__ipHeight-4)
        self.centerNameComboBox.setObjectName("centerNameComboBox")
        # self.centerNameComboBox.setStyleSheet("#centerNameComboBox{border-image:url(%s/settingWindow/passwd.png);background:transparent;color:rgba(200,200,200,255);}"%self.__imagePath)
        # self.centerNameComboBox.setStyleSheet("QComboBox{border-image:url(%s/input.png);background:transparent;}"%self.__imagePath+
        self.centerNameComboBox.setStyleSheet("QComboBox{border-image:url();background:transparent;color:rgba(55,55,55,255);}"+
                                              "QComboBox QAbstractItemView::item { height: %dpx;background-colr: rgba(255,255,255,255);color:rgba(55,55,55,255);}"%(self.__ipHeight-4)+
                                              "QComboBox::down-arrow{image:url(%s/drop_down.png);background:transparent;}"%self.__imagePath+
                                              "QComboBox::drop-down{border:0px;}")
        self.centerNameComboBox.setView(QtGui.QListView())
        centerTop+=self.__ipHeight+self.__ipHeight//2
        self.centerIPLabel=QtGui.QLabel(self.centerGroup)
        self.centerIPLabel.setText('平台IP:'.decode('utf-8'))
        self.centerIPLabel.setFont(contentFont)
        self.centerIPLabel.setGeometry(self.__ipLeftBlank//4,centerTop,self.__ipLeftBlank,self.__ipHeight)
        self.centerIPLabel.setStyleSheet("QLabel{%s}"%self.__labelColor)
        self.centerIPEdit=QtGui.QLineEdit(self.centerGroup)
        # self.centerIPEdit.setEnabled(False)
        # self.centerIPEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.centerIPEdit.setGeometry(self.__ipLeftBlank,centerTop,self.__ipWidth,self.__ipHeight)
        self.centerIPEdit.setStyleSheet(self.__editBackground)
        self.centerIPEdit.setValidator(self.ipValidator)
        centerTop+=self.__ipHeight+self.__ipHeight//2
        self.centerPortLabel=QtGui.QLabel(self.centerGroup)
        self.centerPortLabel.setText('平台端口:'.decode('utf-8'))
        self.centerPortLabel.setFont(contentFont)
        self.centerPortLabel.setGeometry(self.__ipLeftBlank//4,centerTop,self.__ipLeftBlank,self.__ipHeight)
        self.centerPortLabel.setStyleSheet("QLabel{%s}"%self.__labelColor)
        self.centerPortEdit=QtGui.QLineEdit(self.centerGroup)
        # self.centerPortEdit.setEnabled(False)
        # self.centerPortEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.centerPortEdit.setGeometry(self.__ipLeftBlank,centerTop,self.__ipWidth,self.__ipHeight)
        self.centerPortEdit.setStyleSheet(self.__editBackground)
        self.centerPortEdit.setValidator(self.portValidator)

        #初始化平台设置
        self.centerList=[]
        self.defaultCenter={'centerIp':':8080','centerName':'添加新平台'.decode('utf-8')}
        self.getCenter()

        #信息反馈栏
        self.msgLabel=QtGui.QLabel(self)
        self.msgLabel.setGeometry(self.__width//10,
                                  self.__height-self.__height//3,
                                  4*self.__width//5,
                                  self.__ipHeight)
        self.msgLabel.setStyleSheet("QLabel{color:rgba(255,255,255,255)}")
        self.msgLabel.setAlignment(QtCore.Qt.AlignCenter)
        msgFont=QtGui.QFont()
        msgFont.setPointSize(12)
        self.msgLabel.setFont(msgFont)

        # try:
        #     if (self.__networkDic.has_key('carrier') and
        #         self.__networkDic['carrier']=='off'):
        #         self.msgLabel.setText('网线没有插好！'.decode('utf-8'))
        #         self.msgTimer.start(3000)
        #     elif (self.__networkDic.has_key('state') and
        #                 self.__networkDic['state'] == 'disconnected'):
        #         self.msgLabel.setText('网络连接已断开，请检查网络连接！'.decode('utf-8'))
        #         self.msgTimer.start(3000)
        #     elif (self.__networkDic.has_key('isAutoIP') and
        #                 self.__networkDic['address'] == ''):
        #         self.msgLabel.setText('无法自动获取IP地址！'.decode('utf-8'))
        #         self.msgTimer.start(3000)
        #     else:
        #         self.msgLabel.setText('请检查网络设置和平台设置'.decode('utf-8'))
        #         self.msgTimer.start(3000)
        # except Exception,err:
        #     LogRecord.instance().logger.exception("获取本地网络设置发生异常")

        # self.showFullScreen()

    def onAutoIP(self):
        self.isAutoIP = True
        self.ipEdit.setEnabled(False)
        self.gateEdit.setEnabled(False)
        self.subEdit.setEnabled(False)
        self.autoDNS.setEnabled(True)
    def onStaticIP(self):
        self.isAutoIP = False
        self.ipEdit.setEnabled(True)
        self.gateEdit.setEnabled(True)
        self.subEdit.setEnabled(True)
        self.isAutoDNS = False
        self.autoDNS.setEnabled(False)
        self.staticDNS.setChecked(True)
        self.dns1Edit.setEnabled(True)
        self.dns2Edit.setEnabled(True)
    def onAutoDNS(self):
        self.isAutoDNS=True
        self.dns1Edit.setEnabled(False)
        self.dns2Edit.setEnabled(False)
    def onStaticDNS(self):
        self.isAutoDNS=False
        self.dns1Edit.setEnabled(True)
        self.dns2Edit.setEnabled(True)

    def __isDefault(self,netInfo):
        if not isinstance(netInfo,str):
            LogRecord.instance().logger.error("获取网络连接信息错误！")
        try:
            lines=netInfo.splitlines()
            for line in lines:
                if line.find('Default:') >= 0:
                    if line.find('yes') >= 0:
                        return True
        except Exception,err:
            LogRecord.instance().logger.exception("获取网络连接信息错误！")
        return False
    def __isCarrier(self,netInfo):
        if not isinstance(netInfo,str):
            LogRecord.instance().logger.error("获取网络连接信息错误！")
        try:
            lines=netInfo.splitlines()
            for line in lines:
                if line.find('Carrier:') >= 0:
                    if line.find('on') >= 0:
                        return True
        except Exception,err:
            LogRecord.instance().logger.exception("获取网络连接信息错误！")
        return False
    def __getPluggedIns(self):
        netCardNames=[]
        try:
            proc = os.popen('sudo lshw -C net')
            resStr = proc.read()
            proc.close()
            netCardInfos=resStr.split('*-network')
            netCardInfos=netCardInfos[1:]
            for info in netCardInfos:
                try:
                    lines=info.splitlines()
                    name=''
                    for line in lines:
                        if line.find('logical name:') >= 0:
                            strList=line.split('logical name:')
                            name = strList[1].strip()
                        elif line.find('configuration:') >= 0:
                            LogRecord.instance().logger.debug(name+' '+line)
                            if line.find('duplex=full') >= 0:
                                netCardNames.append(name)
                except Exception,err:
                    LogRecord.instance().logger.exception("解析网卡信息异常！")
                    continue
        except Exception,err:
            LogRecord.instance().logger.exception("获取网卡硬件信息异常！")
            return []
        return netCardNames

    def getDefaultNetwork(self,nm_outs):
        self.__networkDic['carrier']='off'
        if not isinstance(nm_outs,str):
            LogRecord.instance().logger.error("获取网络连接信息错误！")
            return ""
        try:
            netInfos=nm_outs.split('- Device:')
            if len(netInfos) < 1:
                LogRecord.instance().logger.error("获取网络连接信息错误！")
                return ""
            self.__networkDic['carrier']='on'
            netInfos = netInfos[1:]
            for i in range(len(netInfos)):
                if i >= len(netInfos):
                    break
                netInfos[i]='- Device:'+netInfos[i]
                if self.__isCarrier(netInfos[i]):
                    if self.__isDefault(netInfos[i]):
                        return netInfos[i]
                else:
                    netInfos.pop(i)
                    i-=1
        except Exception,err:
            LogRecord.instance().logger.exception("解析网络信息错误！")
            self.__networkDic['carrier']='off'
            return ''

        if len(netInfos) > 0:
            return '- Device:'+netInfos[0]
        else:
            LogRecord.instance().logger.info("读取网卡配置信息！")
            netCards=self.__getPluggedIns()
            if len(netCards)<=0:
                self.__networkDic['carrier']='off'
                return ''
            else:
                try:
                    netInfos=nm_outs.split('- Device:')
                    netInfos = netInfos[1:]
                    for i in range(len(netInfos)):
                        netInfos[i]='- Device:'+netInfos[i]
                    for netCard in netCards:
                        for info in netInfos:
                            if info.find(netCard) >= 0:
                                LogRecord.instance().logger.debug(netCard)
                                self.netCardName=netCard
                                return info
                except Exception,err:
                    LogRecord.instance().logger.exception("匹配网卡信息异常！")
                self.__networkDic['carrier']='off'
                return ""

    def __autoIPGetDNS(self):
        self.isAutoDNS=True
        if os.path.exists('/etc/dhcp/dhclient.conf'):
            try:
                f=open('/etc/dhcp/dhclient.conf','r+')
                content=f.read()
                if content.find('prepend domain-name-servers ') >= 0:
                    conLines=content.splitlines(True)
                    for line in conLines:
                        index=line.find('prepend domain-name-servers ')
                        if index >= 0:
                            commentIndex=line.find('#')
                            if (commentIndex >= 0) and (commentIndex < index):
                                continue
                            else:
                                self.isAutoDNS=False
                                dnsString = line[index+len('prepend domain-name-servers '):]
                                try:
                                    endIndex=dnsString.find(';')
                                    if endIndex > 0:
                                        dnsString=dnsString[:endIndex]
                                        DNSs=dnsString.split(',')
                                        LogRecord.instance().logger.debug(DNSs[0]+":::"+DNSs[1])
                                        if self.isIP(DNSs[0]):
                                            self.__networkDic['nameserver']=DNSs[0]
                                        else:
                                            self.__networkDic['nameserver']=''
                                        if self.isIP(DNSs[1]):
                                            self.__networkDic['nameserver1']=DNSs[1]
                                        else:
                                            self.__networkDic['nameserver1']=''
                                except Exception,err:
                                    LogRecord.instance().logger.exception("解析动态IP，静态DNS异常！")

            except Exception,err:
                LogRecord.instance().logger.exception('对文件/etc/dhcp/dhclient.conf的读写操作异常！')
            finally:
                f.close()

    def getLocalNetWork(self):
        """
        获取本地IP设置，显示在界面上
        :return:
        """

        # 判断是静态IP还是动态IP对界面进行初始化 -top
        ip_value = network_set_func.get_local_net_information()
        if len(ip_value) == 5:
            self.staticIP.setChecked(True)
            self.autoIP.setChecked(False)
            self.ipEdit.setText(ip_value[2])
            self.subEdit.setText(ip_value[3])
            self.gateEdit.setText(ip_value[4])
        elif len(ip_value) == 2:
            self.autoIP.setChecked(True)
            self.staticIP.setChecked(False)
            self.isAutoIP = True
            self.ipEdit.setEnabled(False)
            self.gateEdit.setEnabled(False)
            self.subEdit.setEnabled(False)
            self.autoDNS.setEnabled(True)
            ########################################################
            #显示自动获取的ip
            auto_ip = network_set_func.get_auto_ip_list()
            if len(auto_ip) == 3:
                self.ipEdit.setText(auto_ip[0])
                self.subEdit.setText(auto_ip[1])
                self.gateEdit.setText(auto_ip[2])
            ########################################################
        else:
            self.autoIP.setChecked(True)
            self.staticIP.setChecked(False)
            #added by wangshigang
            self.isAutoIP = True
            self.ipEdit.setEnabled(False)
            self.gateEdit.setEnabled(False)
            self.subEdit.setEnabled(False)
            self.autoDNS.setEnabled(True)
            ########################################################
            #显示自动获取的ip
            auto_ip = network_set_func.get_auto_ip_list()
            if len(auto_ip) == 3:
                self.ipEdit.setText(auto_ip[0])
                self.subEdit.setText(auto_ip[1])
                self.gateEdit.setText(auto_ip[2])
            ########################################################
        # 判断是静态IP还是动态IP对界面进行初始化 -end



        # 判断是静态IP还是动态IP对dns界面进行初始化 -top
        dns_value = network_set_func.get_dns_list()
        for i in range(len(dns_value)):
            print dns_value[i]
        #modified by wangshigang
        for i in range(len(dns_value)):
                if i == 0:
                    self.dns1Edit.setText(dns_value[0])
                elif i == 1:
                    self.dns2Edit.setText(dns_value[1])
        if self.staticIP.isChecked():
            self.autoDNS.setDisabled(True)
            self.autoDNS.setChecked(False)
            self.staticDNS.setChecked(True)
            # for i in range(len(dns_value)):
            #     if i == 0:
            #         self.dns1Edit.setText(dns_value[0])
            #     elif i == 1:
            #         self.dns2Edit.setText(dns_value[1])

        elif self.autoIP.isChecked():
            self.autoDNS.setDisabled(False)
            self.autoDNS.setChecked(True)
            self.staticDNS.setChecked(False)
        else:
            self.autoDNS.setDisabled(False)
            self.autoDNS.setChecked(True)
            self.staticDNS.setChecked(False)

        dns_static_or_dhcp = network_set_func.get_dns_dhcp_or_static()
        if dns_static_or_dhcp == "static":
            self.staticDNS.setChecked(True)
            for i in range(len(dns_value)):
                if i == 0:
                    self.dns1Edit.setText(dns_value[0])
                elif i == 1:
                    self.dns2Edit.setText(dns_value[1])
        else:
            self.autoDNS.setChecked(True)
            self.isAutoDNS=True
            self.dns1Edit.setEnabled(False)
            self.dns2Edit.setEnabled(False)

        # 判断是静态IP还是动态IP对dns界面进行初始化 -end


    def __refreshNetCard(self):
        """
        更新可用网卡信息！
        :return:
        """
        try:
            nm_tool_process = subprocess.Popen("nm-tool", stdout=subprocess.PIPE)
            nm_tool_out = nm_tool_process.stdout.read()
            defaultNet = self.getDefaultNetwork(nm_tool_out)
            if defaultNet == '':
                return False
            tool_outs = defaultNet.splitlines()
            try:
                for line in tool_outs:
                    if line.find('Device:') >= 0:
                        netCardName=line.split('Device:',1)[1].strip()
                        self.netCardName=netCardName.split()[0].strip()
            except Exception,err:
                LogRecord.instance().logger.exception("解析网卡异常！")
                return False
        except Exception,err:
            LogRecord.instance().logger.exception('刷新网卡异常！')
            return False

        return True

    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


    def check_DefaultCenter_ip(self):
        conf = UserInfoConfFile()
        default = conf.getDefaultCenter()
        if default == "请选择平台":
            return "no_have"
        else:
            return default

    def _set_dns(self):
        if self.autoDNS.isChecked():
            network_set_func.set_dhcp_dns()
        elif self.staticDNS.isChecked():
            DNS1 = self.dns1Edit.text().trimmed()
            DNS2 = self.dns2Edit.text().trimmed()
            if ((str(DNS1).strip() != '') and
                    (not self.isIP(str(DNS1).strip()))):
                self.msgLabel.setText('首选DNS格式错误！'.decode('utf-8'))
                self.msgTimer.start(3000)
                return False
            if ((str(DNS2).strip() != '') and
                    (not self.isIP(str(DNS2).strip()))):
                self.msgLabel.setText('备用DNS格式错误！'.decode('utf-8'))
                self.msgTimer.start(3000)
                return False
            #modified by wangshigang for deal with first dns is empty but second is not
            if (str(DNS1) == '' and str(DNS2) != ''):
                DNS1 = DNS2
                DNS2 = QtCore.QString("")
            network_set_func.set_static_dns(str(DNS1),str(DNS2))

    def __check_a_ip_input(self,ip,name):
        if ip == '':
            self.msgLabel.setText(('%s不能为空，请输入%s！'%(name,name)).decode('utf-8'))
            self.msgTimer.start(3000)
            return False
        elif not self.isIP(ip):
            self.msgLabel.setText(('输入的%s格式错误，请输入正确的%s！'%(name,name)).decode('utf-8'))
            self.msgTimer.start(3000)
            return False
        else:
            return True

    def __check_input_validate(self):
        if self.staticIP.isChecked():
            ip = str(self.ipEdit.text()).strip()
            if not self.__check_a_ip_input(ip,'IP地址'):
                self.ipEdit.setFocus()
                return False
            netmask = str(self.subEdit.text()).strip()
            if not self.__check_a_ip_input(netmask,'子网掩码'):
                self.subEdit.setFocus()
                return False
            gateway = str(self.gateEdit.text()).strip()
            if not self.__check_a_ip_input(gateway,'网关'):
                self.gateEdit.setFocus()
                return False
        # else:
        #     self.ipEdit.setText('')
        #     self.subEdit.setText('')
        #     self.gateEdit.setText('')
        if self.staticDNS.isChecked():
            DNS1 = str(self.dns1Edit.text()).strip()
            if (DNS1 == ''):
                pass
            elif not self.__check_a_ip_input(DNS1,'首选DNS'):
                self.dns1Edit.setFocus()
                return False
            DNS2 = str(self.dns2Edit.text()).strip()
            if (DNS2 == ''):
                pass
            elif not self.__check_a_ip_input(DNS2,'备用DNS'):
                self.dns2Edit.setFocus()
                return False
        # else:
        #     self.dns1Edit.setText('')
        #     self.dns2Edit.setText('')
        if self.centerIPEdit.isEnabled():
            centerIP = str(self.centerIPEdit.text()).strip()
            if not self.__check_a_ip_input(centerIP,'平台IP'):
                self.centerIPEdit.setFocus()
                return False
            port = str(self.centerPortEdit.text())
            if port.strip() == '':
                self.msgLabel.setText('平台端口不能为空，请输入平台端口！'.decode('utf-8'))
                self.msgTimer.start(3000)
                self.centerPortEdit.setFocus()
                return False
            if not self.isPort(port):
                self.msgLabel.setText('设置的平台端口格式错误!'.decode('utf-8'))
                self.msgTimer.start(3000)
                self.centerPortEdit.setFocus()
                return False
        LogRecord.instance().logger.debug('输入格式验证通过！')
        return True


    def check_static_network(self,defalut_center,ip,subnetMask,gateWay):
        __netcard_list = network_set_func.get_net_card_list()
        for i in range(len(__netcard_list)):
            network_set_func.set_static_network(__netcard_list[i],ip,subnetMask,gateWay)
            network_set_func.set_currnet_netcard_name(__netcard_list[i])
            self._set_dns()
            time.sleep(1)
            for i in range(18):
                centerName = CenterName(defalut_center)
                validate = centerName.getCenterName()
                if validate[0]:
                    print "true"
                    return True
                time.sleep(5)
        return False

    def check_dhcp_network(self,defalut_center):
        __netcard_list = network_set_func.get_net_card_list()
        for i in range(len(__netcard_list)):
            network_set_func.set_dhcp_network(__netcard_list[i])
            network_set_func.set_currnet_netcard_name(__netcard_list[i])
            self._set_dns()
            time.sleep(1)
            for i in range(18):
                centerName = CenterName(defalut_center)
                validate = centerName.getCenterName()
                if validate[0]:
                    print "true"
                    return True
                time.sleep(5)
        return False


    def setNetWork(self):
        """
        设置网络
        :return:输入的网络设置格式是否正确
        """

        ip=str(self.ipEdit.text()).strip()
        subnetMask=str(self.subEdit.text()).strip()
        gateWay=str(self.gateEdit.text()).strip()
        DNS1=str(self.dns1Edit.text()).strip()
        DNS2=str(self.dns2Edit.text()).strip()

        if self.staticDNS.isChecked():
            if DNS1 != "":
                if not self.isIP(DNS1):
                    self.msgLabel.setText('输入的首先DNS格式错误，请输入正确的首选DNS！'.decode('utf-8'))
                    self.msgTimer.start(3000)
                    return False
            if DNS2 != "":
                if not self.isIP(DNS2):
                    self.msgLabel.setText('输入的备用DNS格式错误，请输入正确的备用DNS！'.decode('utf-8'))
                    self.msgTimer.start(3000)
                    return False


        if self.autoIP.isChecked():#如果自动获取网络点中
            """dhcp网络设置"""

            defalut_center = str(self.centerIPEdit.text()).strip()+str(":")+str(self.centerPortEdit.text()).strip()
            retu = self.check_dhcp_network(defalut_center)
            if retu == True:
                return True
            self.msgLabel.setText('网络设置错误！'.decode('utf-8'))
            self.msgTimer.start(3000)
            return False
        elif self.staticIP.isChecked():#如果自动获取网络没有点中
            """非dhcp网络设置"""
            defalut_center = str(self.centerIPEdit.text()).strip()+str(":")+str(self.centerPortEdit.text()).strip()
            retu = self.check_static_network(defalut_center,ip,subnetMask,gateWay)
            if retu == True:
                return  True
            self.msgLabel.setText('网络设置错误！'.decode('utf-8'))
            self.msgTimer.start(3000)
            return False
        else:
            pass
        self.msgLabel.setText('网络设置没有生效！'.decode('utf-8'))
        self.msgTimer.start(3000)
        return False



    @QtCore.pyqtSlot(int)
    def onSelectedCenter(self,index):
        """
        响应选择平台操作
        :param index: 平台索引
        :return:
        """
        try:
            centerName=(self.centerNameComboBox.currentText())
        except Exception,err:
            LogRecord.instance().logger.exception("初始化平台设置异常")
            centerName = self.centerNameComboBox.currentText()

        if centerName == u"添加新平台":
            self.centerIPEdit.setEnabled(True)
            self.centerPortEdit.setEnabled(True)
        else:
            self.centerIPEdit.setEnabled(False)
            self.centerPortEdit.setEnabled(False)
        for center in self.centerList:
            if center['index'] == index:
                try:
                    ip,port=center['centerIp'].split(':',1)
                    self.centerIPEdit.setText(ip)
                    self.centerPortEdit.setText(port)
                except Exception,err:
                    LogRecord.instance().logger.exception("分解平台地址失败！")
                    self.centerIPEdit.setText('')
                    self.centerPortEdit.setText('8080')

    def changeCenter(self,index):
        """
        设置下拉框默认项
        :param index: 默认项索引
        :return:
        """
        self.centerNameComboBox.setCurrentIndex(index)
        self.onSelectedCenter(index)

    def getCenter(self):
        """
        初始化平台显示
        :return:
        """
        try:
            centerList=self.conf.getCenterList()
            if (centerList != None) or (len(centerList) != 0):
                self.centerList = centerList
            newCenter={'centerIp':':8080','centerName':'添加新平台'.decode('utf-8')}
            self.centerList.append(newCenter)
            index=0
            for center in self.centerList:
                if isinstance(center['centerName'],str):
                    self.centerNameComboBox.addItem(center['centerName'].decode('utf-8'))
                else:
                    self.centerNameComboBox.addItem(center['centerName'])
                center['index']=index
                index+=1
            try:
                if len(self.centerList) > 1:
                    default=self.conf.getDefaultCenter()
                    if default == "请选择平台":
                        LogRecord.instance().logger.warn('默认平台配置错误！')
                        try:
                            for center in self.centerList:
                                centerName=CenterName(center['centerIp'])
                                validate=centerName.getCenterName()
                                if validate[0]:
                                    self.conf.setDefaultCenter(center['centerIp'])
                                    self.changeCenter(center['index'])
                                    return
                            self.changeCenter(index-1)
                            return
                        except Exception,err:
                            LogRecord.instance().logger.exception("验证平台错误！")
                            self.changeCenter(index-1)
                            return
                    else:
                        for center in self.centerList:
                            if center["centerIp"] == default:
                                self.changeCenter(center['index'])
                                return
                        self.changeCenter(index-1)
                        return
                else:
                    self.changeCenter(0)
                    return

            except Exception,err:
                LogRecord.instance().logger.exception('获取默认平台异常！')
        except Exception,err:
            LogRecord.instance().logger.exception('获取平台列表异常！')

    def isPort(self,port):
        """
        验证端口是否时有效的端口
        :param port:
        :return:
        """
        portReg=re.compile("^([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])$")
        if not re.match(portReg,port):
            return False
        return True

    def setCenter(self):
        """
        设置平台
        :return:是否成功
        """
        ip = str(self.centerIPEdit.text())
        if ip.strip() == '':
            self.msgLabel.setText('平台IP不能为空，请输入平台IP！'.decode('utf-8'))
            self.msgTimer.start(3000)
            return False
        if not self.isIP(ip):
            self.msgLabel.setText('设置的平台IP格式错误!'.decode('utf-8'))
            self.msgTimer.start(3000)
            return False
        port = str(self.centerPortEdit.text())
        if port.strip() == '':
            self.msgLabel.setText('平台端口不能为空，请输入平台端口！'.decode('utf-8'))
            self.msgTimer.start(3000)
            return False
        if not self.isPort(port):
            self.msgLabel.setText('设置的平台端口格式错误!'.decode('utf-8'))
            self.msgTimer.start(3000)
            return False
        try:
            itemName=str(self.centerNameComboBox.currentText())
        except Exception,err:
            itemName=self.centerNameComboBox.currentText()
        if itemName == '添加新平台':
            try:
                centerIP=ip+':'+port
                LogRecord.instance().logger.info('添加新平台： '+centerIP)
                centerName=CenterName(centerIP)
                validate=centerName.getCenterName()
                if validate[0]:
                    self.conf.addCenter(centerIP,validate[1].encode('utf-8'))
                    if not self.conf.setDefaultCenter(centerIP):
                        self.msgLabel.setText('设置默认平台失败！'.decode('utf-8'))
                        self.msgTimer.start(3000)
                        return False
                    else:
                        return True
                else:
                    self.msgLabel.setText(validate[1].decode('utf-8'))
                    self.msgTimer.start(3000)
                    return False

            except Exception,err:
                LogRecord.instance().logger.exception("添加新平台,验证平台错误！")
                self.msgLabel.setText("添加新平台,验证平台错误！".decode('utf-8'))
                self.msgTimer.start(3000)
                return False
        else:
            try:
                centerIP=ip+':'+port
                LogRecord.instance().logger.info(itemName+u'： '+centerIP)
                centerName=CenterName(centerIP)
                validate=centerName.getCenterName()
                if validate[0]:
                    try:
                        self.conf.addCenter(centerIP,validate[1].encode('utf-8'))
                    except Exception,err:
                        LogRecord.instance().logger.exception(validate[1])
                    if not self.conf.setDefaultCenter(centerIP):
                        self.msgLabel.setText('设置默认平台失败！'.decode('utf-8'))
                        self.msgTimer.start(3000)
                        return False
                    else:
                        return True
                else:
                    self.msgLabel.setText(validate[1].decode('utf-8'))
                    self.msgTimer.start(3000)
                    return False
            except Exception,err:
                LogRecord.instance().logger.exception(itemName+",验证平台错误！".decode('utf-8'))
                self.msgLabel.setText((itemName+",验证平台错误！".decode('utf-8')))
                self.msgTimer.start(3000)
                return False

    def keyPressEvent(self,event):
        if (event.key() == QtCore.Qt.Key_Enter) or (event.key() == QtCore.Qt.Key_Return):
            self.onConfirm()

    @QtCore.pyqtSlot()
    def onMsgTimeout(self):
        self.msgTimer.stop()
        self.msgLabel.setText("")

    def onEmit(self,signal):
        self.emit(QtCore.SIGNAL(signal))

    @QtCore.pyqtSlot()
    def onConfirm(self):
        if not self.__check_input_validate():
            return False
        self.msgLabel.setText('正在设置网络...'.decode('utf-8'))
        self.msgLabel.repaint()
        emitThread=Thread(target=self.onEmit,args=('onSetNetWorkSignal()',))
        emitThread.start()
        self.msgLabel.repaint()

    @QtCore.pyqtSlot()
    def onSetNetwork(self):
        if self.setNetWork():
            self.msgLabel.setText('等待网络设置生效...'.decode('utf-8'))
            self.msgLabel.repaint()
            self.getLocalNetWork()
            emitThread=Thread(target=self.onEmit,args=('onWaitNetWorkSignal()',))
            emitThread.start()
            self.msgLabel.repaint()
            # self.emit(QtCore.SIGNAL('onSetCenterSignal()'))
        else:
            self.getLocalNetWork()
            self.confirmBtn.setEnabled(True)

    def __waitNetworkStart(self):
        nm_process=os.popen('nm-tool')
        nm_results=nm_process.read()
        nm_process.close()
        netInfo=self.getDefaultNetwork(nm_results)
        lines=netInfo.splitlines()
        for line in lines:
            if line.find('State:')>=0:
                LogRecord.instance().logger.debug(line)
                if line.find('disconnected')>=0:
                    self.__networkDic['state']='disconnected'
                elif line.find('connected')>=0:
                    self.__networkDic['state']='connected'
    @QtCore.pyqtSlot()
    def onWaitNetWork(self):
        #等待网络设置生效
        # startTime=time.time()
        # self.__networkDic['state']='disconnected'
        # self.__waitNetworkStart()
        # while self.__networkDic['state'] != 'connected':
        #     time.sleep(1)
        #     if time.time()-startTime > 30:
        #         self.msgLabel.setText('设置网络超时！请检查网络连接！'.decode('utf-8'))
        #         self.msgTimer.start(3000)
        #         return
        #     self.__waitNetworkStart()
        # self.getLocalNetWork()
        # self.getLocalNetWork()
        # while self.__networkDic['address'] == '':
        #     if time.time()-startTime > 30:
        #         self.msgLabel.setText('设置网络超时！请检查网络连接！'.decode('utf-8'))
        #         self.msgTimer.start(3000)
        #         return
        #     self.getLocalNetWork()
        self.msgLabel.setText('正在设置平台...'.decode('utf-8'))
        self.msgLabel.repaint()
        emitThread=Thread(target=self.onEmit,args=('onSetCenterSignal()',))
        emitThread.start()
        self.msgLabel.repaint()

    @QtCore.pyqtSlot()
    def onSetCenter(self):
        if self.setCenter():
            self.getCenter()
            self.msgLabel.setText(''.decode('utf-8'))
            self.confirmBtn.setEnabled(True)
            LogRecord.instance().logger.debug("设置平台成功！！！")
            self.close()
        else:
            self.confirmBtn.setEnabled(True)

    def showFullScreen(self):
        super(ForeSetting, self).showFullScreen()
        self.exec_()  #  阻塞

if __name__ == "__main__":
    import sys
    os.environ["WIN_UI_IMAGES_PATH"]="../../images"
    app = QtGui.QApplication(sys.argv)
    foreDialog=ForeSetting()
    foreDialog.showFullScreen()
    sys.exit(app.exec_())

