#!/usr/bin/python
# coding=utf8

import subprocess
import re

from PyQt4.QtGui import QWidget, QRegExpValidator
from PyQt4.QtCore import Qt, QRegExp, SIGNAL

# from uiWindow.logger import LogRecord

from ui.ui_networkset import Ui_Form
from common import common_run


class NetWokdSetQss(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(NetWokdSetQss, self).__init__(parent)

        self.setupUi(self)
        self.setAttribute(Qt.WA_DeleteOnClose)  # 当窗口关闭时释放内存

        #设置格式判断
        reg = QRegExp('^[0-9\.]{0,15}$')
        validator = QRegExpValidator(reg)
        self.S__IP_LineEdit.setValidator(validator)
        self.S__netMassk_LineEdit.setValidator(validator)
        self.S__gateWay_LineEdit.setValidator(validator)
        self.S__DNS1_LineEdit_4.setValidator(validator)
        self.S__DNS2_LineEdit.setValidator(validator)
        #初始化网络设置显示
        # self.getLocalNetWork()
        # self.detectNetworkState()

        self.autoDNS.setFocusPolicy(Qt.NoFocus)
        self.autoIP.setFocusPolicy(Qt.NoFocus)
        self.staticDNS.setFocusPolicy(Qt.NoFocus)
        self.staticIP.setFocusPolicy(Qt.NoFocus)
        self.connect(self.autoIP, SIGNAL('clicked()'), self.onAutoIP)
        self.connect(self.staticIP, SIGNAL('clicked()'), self.onStaticIP)
        self.connect(self.autoDNS,SIGNAL('clicked()'),self.onAutoDNS)
        self.connect(self.staticDNS,SIGNAL('clicked()'),self.onStaticDNS)
        self.__setstylesheet_2()

    def update_screen_show(self):
        self.__setstylesheet_2()

    def __setstylesheet_2(self):
        self.groupBox_DNS.setMinimumHeight(common_run.get_height(140))
        self.groupBox_DNS.setMaximumHeight(common_run.get_height(140))
        self.groupBox_IP.setMinimumHeight(common_run.get_height(170))
        self.groupBox_IP.setMaximumHeight(common_run.get_height(170))
        self.verticalLayout_9.setContentsMargins(int(common_run.get_width(60.0)),
                                               int(common_run.get_height(20.0)),
                                               int(common_run.get_width(40.0)),
                                               int(common_run.get_height(40.0)))
        self.verticalLayout_9.setSpacing(int(common_run.get_width(10.0)))

        self.verticalLayout_3.setContentsMargins(int(common_run.get_width(20.0)),
                                                 int(common_run.get_height(20.0)),
                                               int(common_run.get_width(120.0)),
                                               int(common_run.get_height(20.0)))

        self.verticalLayout_7.setContentsMargins(int(common_run.get_width(20.0)),
                                               int(common_run.get_height(20.0)),
                                               int(common_run.get_width(120.0)),
                                               int(common_run.get_height(20.0)))


        self.S__IP_LineEdit.setMaximumWidth(int(common_run.get_width(350.0)))
        self.S__IP_LineEdit.setMaximumHeight(int(common_run.get_height(30.0)))
        self.S__gateWay_LineEdit.setMaximumWidth(int(common_run.get_width(350.0)))
        self.S__gateWay_LineEdit.setMaximumHeight(int(common_run.get_height(30.0)))
        self.S__netMassk_LineEdit.setMaximumWidth(int(common_run.get_width(350.0)))
        self.S__netMassk_LineEdit.setMaximumHeight(int(common_run.get_height(30.0)))
        self.S__DNS1_LineEdit_4.setMaximumWidth(int(common_run.get_width(350.0)))
        self.S__DNS1_LineEdit_4.setMaximumHeight(int(common_run.get_height(30.0)))
        self.S__DNS2_LineEdit.setMaximumWidth(int(common_run.get_width(350.0)))
        self.S__DNS2_LineEdit.setMaximumHeight(int(common_run.get_height(30.0)))

        __font_size = str(int(common_run.get_height(12.0)))
        self.setStyleSheet("font: 63 "+__font_size+"pt \"ubuntu\" ;")
        self.S__IP_LineEdit.setStyleSheet('border:1px groove rgb(200,200,200);')
        self.S__gateWay_LineEdit.setStyleSheet('border:1px groove rgb(200,200,200);')
        self.S__netMassk_LineEdit.setStyleSheet('border:1px groove rgb(200,200,200);')
        self.S__DNS1_LineEdit_4.setStyleSheet('border:1px groove rgb(200,200,200);')
        self.S__DNS2_LineEdit.setStyleSheet('border:1px groove rgb(200,200,200);')
        self.verticalLayout_6.setSpacing(int(common_run.get_height(5.0)))
        self.verticalLayout.setSpacing(int(common_run.get_height(5.0)))
        self.horizontalLayout.setSpacing(int(common_run.get_height(40.0)))
        self.horizontalLayout_3.setSpacing(int(common_run.get_height(40.0)))

    def onAutoIP(self):
        self.isAutoIP = True
        self.S__IP_LineEdit.setEnabled(False)
        self.S__gateWay_LineEdit.setEnabled(False)
        self.S__netMassk_LineEdit.setEnabled(False)
        self.autoDNS.setEnabled(True)
    def onStaticIP(self):
        self.isAutoIP = False
        self.S__IP_LineEdit.setEnabled(True)
        self.S__gateWay_LineEdit.setEnabled(True)
        self.S__netMassk_LineEdit.setEnabled(True)
        self.isAutoDNS = False
        self.autoDNS.setEnabled(False)
        self.staticDNS.setChecked(True)
        self.S__DNS1_LineEdit_4.setEnabled(True)
        self.S__DNS2_LineEdit.setEnabled(True)
    def onAutoDNS(self):
        self.isAutoDNS=True
        self.S__DNS1_LineEdit_4.setEnabled(False)
        self.S__DNS2_LineEdit.setEnabled(False)
    def onStaticDNS(self):
        self.isAutoDNS=False
        self.S__DNS1_LineEdit_4.setEnabled(True)
        self.S__DNS2_LineEdit.setEnabled(True)


    # def getLocalNetWork(self):
    #     """
    #     获取本地IP设置，显示在界面上
    #     :return:
    #     """
    #     self.netCardName=''
    #     self.isAutoIP = False
    #     self.isAutoDNS = False
    #     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()
    #         tool_outs = nm_tool_out.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:
    #                     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
    #                     netCardName=line.split('Device:',2)[1]
    #                     self.netCardName=netCardName.split('[',2)[0].strip()
    #         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'])
    #     if self.isAutoIP:
    #         self.autoIP.setChecked(True)
    #         self.S__IP_LineEdit.setEnabled(False)
    #         self.S__gateWay_LineEdit.setEnabled(False)
    #         self.S__netMassk_LineEdit.setEnabled(False)
    #     else:
    #         self.staticIP.setChecked(True)
    #         self.S__IP_LineEdit.setEnabled(True)
    #         self.S__gateWay_LineEdit.setEnabled(True)
    #         self.S__netMassk_LineEdit.setEnabled(True)
    #     if self.isAutoDNS:
    #         self.autoDNS.setChecked(True)
    #         self.S__DNS1_LineEdit_4.setEnabled(False)
    #         self.S__DNS2_LineEdit.setEnabled(False)
    #     else:
    #         self.staticDNS.setChecked(True)
    #         self.S__DNS1_LineEdit_4.setEnabled(True)
    #         self.S__DNS2_LineEdit.setEnabled(True)
    #     LogRecord.instance().logger.debug(ipDic)


if __name__ == "__main__":
    from PyQt4 import QtGui
    from os import environ

    environ["WIN_UI_IMAGES_PATH"] = "../../../images"
    app = QtGui.QApplication([])
    win = NetWokdSetQss()
    win.show()
    app.exec_()
