#!/usr/bin/python
#coding=utf-8


import subprocess
import re
from ui_qss.netWorkSetQss import NetWokdSetQss
from modifyNetWork import modifyNetWork
from PyQt4.QtCore import SIGNAL
from common.info_dialog import InfoDialog
from logger.logrecord import LogRecord
import os
import time
from threading import Thread
from common import network_set_func

class NetWokdSet(NetWokdSetQss):
    def __init__(self):
        super(NetWokdSet, self).__init__()
        self.connect(self,SIGNAL('waitEffectSignal'),self.waitEffect)
        self.connect(self,SIGNAL('clearInfoSignal'),self.clearInfo)
        self.connect(self,SIGNAL('waitTimeout'),self.waitTimeout)
        self._init_local_network()
        self.__init_network_status()

    def _init_local_network(self):
        net_value = network_set_func.get_local_net_information()
        if len(net_value) == 2:
            self.autoIP.setChecked(True)
            self.staticIP.setChecked(False)
            self.S__IP_LineEdit.setEnabled(False)
            self.S__gateWay_LineEdit.setEnabled(False)
            self.S__netMassk_LineEdit.setEnabled(False)
            self.autoDNS.setEnabled(True)
            ########################################################
            #显示自动获取的ip
            auto_ip = network_set_func.get_auto_ip_list()
            if len(auto_ip) == 3:
                self.S__IP_LineEdit.setText(auto_ip[0])
                self.S__netMassk_LineEdit.setText(auto_ip[1])
                self.S__gateWay_LineEdit.setText(auto_ip[2])
            ########################################################

        if len(net_value) == 5:
            self.autoIP.setChecked(False)
            self.staticIP.setChecked(True)
            self.autoDNS.setChecked(False)
            self.staticDNS.setChecked(True)
            self.autoDNS.setDisabled(True)
            self.S__IP_LineEdit.setText(net_value[2])
            self.S__netMassk_LineEdit.setText(net_value[3])
            self.S__gateWay_LineEdit.setText(net_value[4])
            # dns_value = network_set_func.get_dns_list()
            # for i in range(len(dns_value)):
            #     if i == 0:
            #         self.S__DNS1_LineEdit_4.setText(dns_value[0])
            #     if i == 1:
            #         self.S__DNS2_LineEdit.setText(dns_value[1])
        #modified by wangshigang
        dns_value = network_set_func.get_dns_list()
        for i in range(len(dns_value)):
            if i == 0:
                self.S__DNS1_LineEdit_4.setText(dns_value[0])
            if i == 1:
                self.S__DNS2_LineEdit.setText(dns_value[1])

        dhcp_or_static_dns_value = network_set_func.get_dns_dhcp_or_static()
        if dhcp_or_static_dns_value == "dhcp":
            self.autoDNS.setChecked(True)
            self.staticDNS.setChecked(False)
            self.S__DNS1_LineEdit_4.setEnabled(False)
            self.S__DNS2_LineEdit.setEnabled(False)
        elif dhcp_or_static_dns_value == "static":
            self.autoDNS.setChecked(False)
            self.staticDNS.setChecked(True)
            self.S__DNS1_LineEdit_4.setEnabled(True)
            self.S__DNS2_LineEdit.setEnabled(True)
            # dns_value = network_set_func.get_dns_list()
            # for i in range(len(dns_value)):
            #     if i == 0:
            #         self.S__DNS1_LineEdit_4.setText(dns_value[0])
            #     if i == 1:
            #         self.S__DNS2_LineEdit.setText(dns_value[1])
        else:
            self.autoDNS.setChecked(True)
            self.staticDNS.setChecked(False)
            self.S__DNS1_LineEdit_4.setEnabled(False)
            self.S__DNS2_LineEdit.setEnabled(False)


    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_a_ip_input(self,ip,name):
        if ip == '':
            InfoDialog.instance().Information(u'提示', ('%s不能为空，请输入%s！'%(name,name)).decode('utf-8'))  # 仅仅 提示信息
            return False
        elif not self.isIP(ip):
            InfoDialog.instance().Information(u'提示', ('输入的%s格式错误，请输入正确的%s！'%(name,name)).decode('utf-8'))  # 仅仅 提示信息
            return False
        else:
            return True

    def __check_input_validate(self):
        if self.staticIP.isChecked():
            ip = str(self.S__IP_LineEdit.text()).strip()
            if not self.__check_a_ip_input(ip,'IP地址'):
                self.S__IP_LineEdit.setFocus()
                return False
            netmask = str(self.S__netMassk_LineEdit.text()).strip()
            if not self.__check_a_ip_input(netmask,'子网掩码'):
                self.S__netMassk_LineEdit.setFocus()
                return False
            gateway = str(self.S__gateWay_LineEdit.text()).strip()
            if not self.__check_a_ip_input(gateway,'网关'):
                self.S__gateWay_LineEdit.setFocus()
                return False
        # else:
        #     self.S__IP_LineEdit.setText('')
        #     self.S__netMassk_LineEdit.setText('')
        #     self.S__gateWay_LineEdit.setText('')
        if self.staticDNS.isChecked():
            DNS1 = str(self.S__DNS1_LineEdit_4.text()).strip()
            if (DNS1 == ''):
                pass
            elif not self.__check_a_ip_input(DNS1,'首选DNS'):
                self.S__DNS1_LineEdit_4.setFocus()
                return False
            DNS2 = str(self.S__DNS2_LineEdit.text()).strip()
            if (DNS2 == ''):
                pass
            elif not self.__check_a_ip_input(DNS2,'备用DNS'):
                self.S__DNS2_LineEdit.setFocus()
                return False
        # else:
        #     self.S__DNS1_LineEdit_4.setText('')
        #     self.S__DNS2_LineEdit.setText('')

        LogRecord.instance().logger.debug('输入格式验证通过！')
        return True

    def __check_input_changed(self):
        _ipcheck = ""
        _dnscheck = ""

        if self.autoIP.isChecked():
            _ipcheck = "dhcp"
        else:
            _ipcheck = "static"

        if self.autoDNS.isChecked():
            _dnscheck = "dhcp"
        else:
            _dnscheck = "static"

        ip=str(self.S__IP_LineEdit.text()).strip()
        subnetMask=str(self.S__netMassk_LineEdit.text()).strip()
        gateWay=str(self.S__gateWay_LineEdit.text()).strip()

        DNS1=str(self.S__DNS1_LineEdit_4.text()).strip()
        DNS2=str(self.S__DNS2_LineEdit.text()).strip()

        if (_ipcheck != self._com_ipcheck or
            _dnscheck != self._com_dnscheck):
            return True
        else:
            if (_ipcheck == 'static'):
                 if (self._com_ip != ip or
                     self._com_subnetMask != subnetMask or
                     self._com_gateWay != gateWay):
                     return True
            if (_dnscheck == 'static'):
                if (self._com_dns1 != DNS1 or
                    self._com_dns2 != DNS2):
                    return True
            if (_ipcheck == 'dhcp'):
                if (self._com_ip != ip or
                     self._com_subnetMask != subnetMask or
                     self._com_gateWay != gateWay):
                    LogRecord.instance().logger.debug("_ipcheck == 'dhcp'")
                    self._init_local_network()
            if (_dnscheck == 'dhcp'):
                if (self._com_dns1 != DNS1 or
                    self._com_dns2 != DNS2):
                    LogRecord.instance().logger.debug("_dnscheck == 'dhcp'")
                    self._init_local_network()
            return False

    # ---------------------------for new function for set network -top

    def _set_dns(self):
        if self.autoDNS.isChecked():
            network_set_func.set_dhcp_dns()
        elif self.staticDNS.isChecked():
            DNS1=str(self.S__DNS1_LineEdit_4.text()).strip()
            DNS2=str(self.S__DNS2_LineEdit.text()).strip()
            #modified by wangshigang for deal with first dns is empty but second is not
            if (DNS1 == '' and DNS2 != ''):
                DNS1 = DNS2
                DNS2 = ''
            network_set_func.set_static_dns(DNS1,DNS2)

    def __init_network_status(self):
        self._com_ip=str(self.S__IP_LineEdit.text())
        self._com_subnetMask=str(self.S__netMassk_LineEdit.text())
        self._com_gateWay=str(self.S__gateWay_LineEdit.text())
        self._com_dns1 = str(self.S__DNS1_LineEdit_4.text())
        self._com_dns2 = str(self.S__DNS2_LineEdit.text())
        if self.autoIP.isChecked():
            self._com_ipcheck = "dhcp"
        else:
            self._com_ipcheck = "static"
        if self.autoDNS.isChecked():
            self._com_dnscheck = "dhcp"
        else:
            self._com_dnscheck = "static"

    def setNetWork(self):
        if not self.__check_input_changed():
            LogRecord.instance().logger.debug('network set is not changed!')
            return True
        if not self.__check_input_validate():
            return False

        ip=str(self.S__IP_LineEdit.text()).strip()
        subnetMask=str(self.S__netMassk_LineEdit.text()).strip()
        gateWay=str(self.S__gateWay_LineEdit.text()).strip()

        current_netcard_name = network_set_func.get_currnet_netcard_name()
        current_netcard_name = str(current_netcard_name)
        if self.autoIP.isChecked():#如果自动获取网络点中
            """dhcp网络设置"""
            network_set_func.set_dhcp_network(current_netcard_name)
            self._set_dns()
        elif self.staticIP.isChecked():#如果自动获取网络没有点中
            """非dhcp网络设置"""
            network_set_func.set_static_network(current_netcard_name,ip,subnetMask,gateWay)
            self._set_dns()
        else:
            pass
        self.__init_network_status()
        self._init_local_network()
        InfoDialog.instance().Information(u'提示',u'网络设置完成！'.decode('utf-8'))
        return True

    # ---------------------------for new function for set network -top


    # def setNetWork(self):
    #     ip=self.S__IP_LineEdit.text()
    #     subnetMask=self.S__netMassk_LineEdit.text()
    #     gateWay=self.S__gateWay_LineEdit.text()
    #     DNS1=self.S__DNS1_LineEdit_4.text()
    #     DNS2=self.S__DNS2_LineEdit.text()
    #     if self.autoIP.isChecked():
    #         if self.__networkDic['isAutoIP'] != "True":
    #             if self.autoDNS.isChecked():
    #                 if self.__networkDic['isAutoDNS'] != "True":
    #                     if not self.__refreshNetCard():
    #                         InfoDialog.instance().Information(u'提示', u'没有插网线！')  # 仅仅 提示信息
    #                         return False
    #                     modifyNetWork.setAutoDNS(self.netCardName)
    #             else:
    #                 if ((str(DNS1).strip() != '') and
    #                     (not self.isIP(str(DNS1).strip()))):
    #                     InfoDialog.instance().Information(u'提示', u'首选DNS格式错误！')  # 仅仅 提示信息
    #                     return False
    #                 if ((str(DNS2).strip() != '') and
    #                         (not self.isIP(str(DNS2).strip()))):
    #                     InfoDialog.instance().Information(u'提示', u'备用DNS格式错误！')  # 仅仅 提示信息
    #                     return False
    #                 modifyNetWork.setAutoIP(DNS1,DNS2)
    #         elif (self.autoDNS.isChecked()):
    #             if (self.__networkDic['isAutoDNS'] != "True"):
    #                 if not self.__refreshNetCard():
    #                     InfoDialog.instance().Information(u'提示', u'没有插网线！')  # 仅仅 提示信息
    #                     return False
    #                 modifyNetWork.setAutoDNS(self.netCardName)
    #         elif ((self.__networkDic['isAutoDNS'] == "True") or
    #                   (DNS1 != self.__networkDic['nameserver']) or
    #                    (DNS2 != self.__networkDic['nameserver1']) ):
    #             if ((str(DNS1).strip() != '') and
    #                     (not self.isIP(str(DNS1).strip()))):
    #                 InfoDialog.instance().Information(u'提示', u'首选DNS格式错误！')  # 仅仅 提示信息
    #                 return False
    #             if ((str(DNS2).strip() != '') and
    #                     (not self.isIP(str(DNS2).strip()))):
    #                 InfoDialog.instance().Information(u'提示', u'备用DNS格式错误！')  # 仅仅 提示信息
    #                 return False
    #             modifyNetWork.setAutoIP(DNS1,DNS2)
    #     else:
    #         if str(ip).strip() == '':
    #             InfoDialog.instance().Information(u'提示', u'IP地址不能为空！')  # 仅仅 提示信息
    #             return False
    #         if not self.isIP(str(ip).strip()):
    #             InfoDialog.instance().Information(u'提示', u'IP地址格式错误！')  # 仅仅 提示信息
    #             return False
    #         if str(subnetMask).strip() == '':
    #             InfoDialog.instance().Information(u'提示', u'子网掩码不能为空！')  # 仅仅 提示信息
    #             return False
    #         if not self.isIP(str(subnetMask).strip()):
    #             InfoDialog.instance().Information(u'提示', u'子网掩码格式错误！')  # 仅仅 提示信息
    #             return False
    #         if str(gateWay).strip() == '':
    #             InfoDialog.instance().Information(u'提示', u'网关不能为空！')  # 仅仅 提示信息
    #             return False
    #         if not self.isIP(str(gateWay).strip()):
    #             InfoDialog.instance().Information(u'提示', u'网关格式错误！')  # 仅仅 提示信息
    #             return False
    #         if ((str(DNS1).strip() != '') and
    #                 (not self.isIP(str(DNS1).strip()))):
    #             InfoDialog.instance().Information(u'提示', u'首选DNS格式错误！')  # 仅仅 提示信息
    #             return False
    #         if ((str(DNS2).strip() != '') and
    #                 (not self.isIP(str(DNS2).strip()))):
    #             InfoDialog.instance().Information(u'提示', u'备用DNS格式错误！')  # 仅仅 提示信息
    #             return False
    #         if (self.__networkDic['isAutoIP'] != "True"):
    #             if((ip != self.__networkDic['address']) or
    #                 (subnetMask != self.__networkDic['netmask']) or
    #                 (gateWay != self.__networkDic['gateway']) or
    #                 (DNS1 != self.__networkDic['nameserver']) or
    #                 (DNS2 != self.__networkDic['nameserver1']) ):
    #                 if not self.__refreshNetCard():
    #                     InfoDialog.instance().Information(u'提示', u'没有插网线！')  # 仅仅 提示信息
    #                     return False
    #                 modifyNetWork.setStaticIP(self.netCardName,ip,subnetMask,gateWay,DNS1,DNS2)
    #         else:
    #             if not self.__refreshNetCard():
    #                 InfoDialog.instance().Information(u'提示', u'没有插网线！')  # 仅仅 提示信息
    #                 return False
    #             modifyNetWork.setStaticIP(self.netCardName,ip,subnetMask,gateWay,DNS1,DNS2)
    #     LogRecord.instance().logger.debug('ip=%s,子网掩码=%s,网关=%s,首选DNS=%s,备用DNS=%s'%(ip,subnetMask,gateWay,DNS1,DNS2))
    #     self.label_info.setText(u"等待网络设置生效...")
    #     self.label_info.repaint()
    #     self.label_info.repaint()
    #     waitEffectThread=Thread(target=self.startWait)
    #     waitEffectThread.setDaemon(True)
    #     waitEffectThread.start()
    #     return True

    def clearInfo(self):
        self.label_info.setText('')

    def startWait(self):
        self.emit(SIGNAL('waitEffectSignal'))

    def waitTimeout(self):
        self.emit(SIGNAL('clearInfoSignal'))
        self.emit(SIGNAL('networkFinishedSingnal'),True)
        InfoDialog.instance().Information(u'提示', u'设置网络超时！请检查网络连接！')  # 仅仅 提示信息

    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'

    def waitEffect(self):
        #等待网络设置生效
        startTime=time.time()
        self.__networkDic['state']='disconnected'
        self.__waitNetworkStart()
        while self.__networkDic['state'] != 'connected':
            time.sleep(1)
            if time.time()-startTime > 30:
                self.emit(SIGNAL('waitTimeout'))
                return
            self.__waitNetworkStart()
        self.getLocalNetWork()
        self.emit(SIGNAL('clearInfoSignal'))
        self.emit(SIGNAL('networkFinishedSingnal'),False)

    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:
            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 getLocalNetWork(self):
        """
        获取本地IP设置，显示在界面上
        :return:
        """

        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.netCardName=''
        self.isAutoIP = False
        self.isAutoDNS = True
        has_a_dns = False
        ipstr = '([0-9]{1,3}\.){3}[0-9]{1,3}'
        ipDic = {}
        ipDic['address'] = ''
        ipDic['netmask'] = ''
        ipDic['gateway'] = ''
        ipDic['nameserver'] = ''
        ipDic['nameserver1'] = ''
        ip_pattern = re.compile('Address:.*')
        netmask_pattern = re.compile('Prefix:.*')
        gateway_pattern = re.compile('Gateway:.*')
        dns_pattern = re.compile('DNS:.*')
        pattern = re.compile(ipstr)
        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 == '':
                raise "nm-tool failed!"
            tool_outs = defaultNet.splitlines()
            try:
                for line in tool_outs:
                    if line.find('Address:') >= 0:
                        for ipaddr in re.finditer(ip_pattern, str(line)):
                            ip = pattern.search(ipaddr.group())
                            if ip == None:
                                break
                            if ip.group() != "127.0.0.1":
                                ipDic['address'] = ip.group()
                    elif line.find('Prefix:') >= 0:
                        for mask in re.finditer(netmask_pattern, str(line)):
                            ip = pattern.search(mask.group())
                            if ip == None:
                                break
                            if ip.group() != "255.0.0.0":
                                ipDic['netmask'] = ip.group()
                    elif line.find('Gateway:') >= 0:
                        for gateWay in re.finditer(gateway_pattern, str(line)):
                            ip = pattern.search(gateWay.group())
                            if ip == None:
                                break
                            ipDic['gateway'] = ip.group()
                    elif line.find('DNS:') >= 0:
                        if (self.isAutoIP and
                                (not self.isAutoDNS)):
                            continue
                        for dns in re.finditer(dns_pattern, str(line)):
                            ip = pattern.search(dns.group())
                            if ip == None:
                                break
                            if not has_a_dns:
                                ipDic['nameserver'] = ip.group()
                                has_a_dns = True
                            else:
                                ipDic['nameserver1'] = ip.group()
                    elif line.find('Device:') >= 0:
                        if line.find('Ifupdown') >= 0:
                            self.isAutoIP = False
                            self.isAutoDNS = False
                        else:
                            self.isAutoIP = True
                            self.__autoIPGetDNS()      #获取静态DNS
                            if not self.isAutoDNS:
                                ipDic['nameserver'] = self.__networkDic['nameserver']
                                ipDic['nameserver1'] = self.__networkDic['nameserver1']
                        netCardName=line.split('Device:',1)[1].strip()
                        self.netCardName=netCardName.split()[0].strip()
                    elif line.find('State:')>=0:
                        if line.find('disconnected')>=0:
                            self.__networkDic['state']='disconnected'
                        elif line.find('connected')>=0:
                            self.__networkDic['state']='connected'
            except Exception, err:
                LogRecord.instance().logger.exception("获取本地网络设置失败！")
        except Exception,err:
            LogRecord.instance().logger.exception("执行命令nm-tool失败！")
        # if ipDic['nameserver1'] == '':
        #     ipDic['nameserver1']=ipDic['nameserver']
        self.S__IP_LineEdit.setText(ipDic['address'])
        self.S__netMassk_LineEdit.setText(ipDic['netmask'])
        self.S__gateWay_LineEdit.setText(ipDic['gateway'])
        self.S__DNS1_LineEdit_4.setText(ipDic['nameserver'])
        self.S__DNS2_LineEdit.setText(ipDic['nameserver1'])
        self.__networkDic['address']=ipDic['address']
        self.__networkDic['netmask']=ipDic['netmask']
        self.__networkDic['gateway']=ipDic['gateway']
        self.__networkDic['nameserver']=ipDic['nameserver']
        self.__networkDic['nameserver1']=ipDic['nameserver1']
        if os.path.exists('/etc/network/interfaces'):
            try:
                f=open('/etc/network/interfaces','r')
                interfaces=f.read()
                conLines=interfaces.splitlines(True)
                for line in conLines:
                    if line.find('dns-nameservers') >= 0:
                        if not line.startswith('#'):
                            self.isAutoDNS=False
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/network/interfaces的读写操作异常！')
            finally:
                f.close()
        if self.isAutoIP:
            self.autoIP.setChecked(True)
            self.autoDNS.setEnabled(True)
            self.S__IP_LineEdit.setEnabled(False)
            self.S__gateWay_LineEdit.setEnabled(False)
            self.S__netMassk_LineEdit.setEnabled(False)
            self.__networkDic['isAutoIP']='True'
        else:
            self.staticIP.setChecked(True)
            self.autoDNS.setEnabled(False)
            self.S__IP_LineEdit.setEnabled(True)
            self.S__gateWay_LineEdit.setEnabled(True)
            self.S__netMassk_LineEdit.setEnabled(True)
            self.__networkDic['isAutoIP']='False'
        if self.isAutoDNS:
            self.autoDNS.setChecked(True)
            self.S__DNS1_LineEdit_4.setEnabled(False)
            self.S__DNS2_LineEdit.setEnabled(False)
            self.__networkDic['isAutoDNS']='True'
        else:
            self.staticDNS.setChecked(True)
            self.S__DNS1_LineEdit_4.setEnabled(True)
            self.S__DNS2_LineEdit.setEnabled(True)
            self.__networkDic['isAutoDNS']='False'
        LogRecord.instance().logger.debug(ipDic)

    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 __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 detectNetworkState(self):
    #     try:
    #         if (self.__networkDic.has_key('carrier') and
    #             self.__networkDic['carrier']=='off'):
    #             InfoDialog.instance().Information(u'提示', u'网线没有插好！')  # 仅仅 提示信息
    #             return False
    #         elif (self.__networkDic.has_key('state') and
    #                     self.__networkDic['state'] == 'disconnected'):
    #             InfoDialog.instance().Information(u'提示', u'网络连接已断开，请检查网络连接！')  # 仅仅 提示信息
    #             return False
    #         elif (self.__networkDic.has_key('isAutoIP') and
    #                     self.__networkDic['address'] == ''):
    #             InfoDialog.instance().Information(u'提示', u'无法自动获取IP地址！')  # 仅仅 提示信息
    #             return False
    #     except Exception,err:
    #         LogRecord.instance().logger.exception("获取本地网络设置发生异常")
    #         InfoDialog.instance().Information(u'提示', u'获取本地网络设置发生异常！')  # 仅仅 提示信息
    #         return False
    #     return True

###############################
#   单元测试
##############################
if __name__ == "__main__":
    from PyQt4 import QtGui
    from os import environ
    environ["WIN_UI_IMAGES_PATH"]="../../../images3"
    app = QtGui.QApplication([])
    win = NetWokdSet()
    win.show()
    app.exec_()
