#coding=utf-8
from PyQt4.QtGui import QWidget,QTableWidgetItem,QAbstractItemView,QDialog
from view.setting.wirednetwork import Ui_Form
from common.logrecord import LogRecord
from model.setting.getnetinfo import NetCtl
from model.setting.netSwitchThread import NetSwitchTd
# from model.setting.base.infohintdialog import InfoHintDialog
from common.infohintdialog import InfoHintDialog
# from model.setting.base.messagebox import MessageBox
from common.messagebox import MessageBox
from view.setting.waitdlg import WaitingWidget
from PyQt4.QtCore import SIGNAL,QString,Qt
import model.setting
import re
 
class WiredNetwork(QWidget,Ui_Form):
    def __init__(self):
        super(WiredNetwork,self).__init__()
        self.setupUi(self)
        self.twNetwork.horizontalHeader().setStretchLastSection(True)
        self.twNetwork.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.twNetwork.setSelectionMode(QAbstractItemView.SingleSelection)
        self.twNetwork.hideColumn(4)
        self.twNetwork.setColumnWidth(0,120)
        self.twNetwork.setColumnWidth(1,120)
        self.twNetwork.setColumnWidth(2,120)
        self.twNetwork.setColumnWidth(3,120)
        self.addstaticAddr.setChecked(True)
        
        self.netCtl = NetCtl()
        self.netSwitchTd = NetSwitchTd()
        self.waitDlg = WaitingWidget()
        self.refreshNetCard()#获取网卡列表
        self.refreshNetWidget()#获取网络列表
        
        self.connect(self.addButton, SIGNAL("clicked()"),self.on_pushButtonAddNetaddress_clicked)
        self.connect(self.deleteButton, SIGNAL("clicked()"),self.on_pushButtonNetworkDel_clicked)
        self.connect(self.startButton, SIGNAL("clicked()"),self.on_pushButtonNetworkStart_clicked)
        self.connect(self.addstaticAddr, SIGNAL("clicked()"),self.setStatic)
        self.connect(self.adddynamicAddr, SIGNAL("clicked()"),self.setDynamic)
        self.connect(self.netSwitchTd, SIGNAL("restartNetworkSignal"),self.showRestartNetworkInfo)
        self.lineEditNetmask.setText("255.255.255.0")
        self.setStyleSheet(QString("QLineEdit{border:1px groove rgb(170,214,252);height:25;}"))
        self.netCardComboBox.setStyleSheet(QString("border:1px groove rgb(170,214,252);height:25;"))

        
    def showRestartNetworkInfo(self,result):
        if (result == 0):
            self.waitDlg.close()
            InfoHintDialog(u"网络重启完成！").exec_()
            self.emit(SIGNAL("wireRestartNetworkSignal"),0)#发射信号更新中心的网络列表
            #得到当前的网络信息
            curNetInfo = self.netCtl.getCurrentNetworkInfo()
            #读取网络地址信息
            netAddressList = self.netCtl.getNetAddressList()
            num = len(netAddressList)
            self.twNetwork.setRowCount(num)
            if( 0 == num ):
                return
            for i in range(num):#更新网络列表
                self.settwIPListRowData(i, netAddressList[i], curNetInfo)
        elif (result == 1):
            return
        elif (result == -1):
            self.waitDlg.close()
            InfoHintDialog(u"网络重启失败！").exec_()
            return
        else:
            self.waitDlg.close()
            InfoHintDialog(u"网络重启失败！").exec_()
            return
        
    def on_pushButtonNetworkStart_clicked(self):#启用某个网络
        LogRecord.instance().recordLog(u"点击启用")
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u"请选择相应的网络！").exec_()
            return
        #获取当前网络的信息
        currentRow = self.twNetwork.currentRow()
        item = self.twNetwork.item(currentRow, 4)
        print item.text(),"this is item ..."
        if (item != ""):
            addressID = item.text()
            #重启网络
            self.netSwitchTd.setNetID(addressID)
            self.netSwitchTd.setFunType("RESTART_NET_SERVERS")
            LogRecord.instance().recordLog(u"启动重启网络的线程")
            self.netSwitchTd.start()
            self.waitDlg.setTip(u"重启网络中...")
            self.waitDlg.show()
            self.waitDlg.move(model.setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
        
    def on_pushButtonNetworkDel_clicked(self):#删除网络
        LogRecord.instance().recordLog(u"点击删除网络按钮")
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u"请选择相应的网络！").exec_()
            return
        LogRecord.instance().recordLog(u"删除网络")
        self.deleteIPAddress()
        self.emit(SIGNAL("updateCenterSetNetCard"))
        
    def deleteIPAddress(self):
        if(MessageBox(u"确定删除该网络吗?").exec_() == QDialog.Rejected):
            return
        currentRow = self.twNetwork.currentRow()
        item = self.twNetwork.item(currentRow,0)
        if (item != ""):
            tempNamee = item.text()
            LogRecord.instance().recordLog(u"进入getnetinfo的delNetAddressItem函数")
            result = self.netCtl.delNetAddressItem(tempNamee)
            if (result == -1):
                InfoHintDialog(u"删除网络失败!").exec_()
                return
            elif (result == -2):
                InfoHintDialog(u"正被使用中!").exec_()
                return
            elif (result == -3):
                InfoHintDialog(u"该网络已被中心使用!").exec_()
                return
            else:
                #刷新表格内容
                #读取网络地址信息
                LogRecord.instance().recordLog(u"获取文件中网络列表")
                netAddressList = self.netCtl.getNetAddressList()
                num = len(netAddressList)
                self.twNetwork.setRowCount(num)
                if( 0 == num ):
                    self.emit(SIGNAL("refresh_center_net"),num,netAddressList)#发送信号更新中心的可选网络列表
                    InfoHintDialog(u"删除成功!").exec_()
                    return
                #得到当前的网络信息
                LogRecord.instance().recordLog(u"获取当前网络")
                curNetInfo = self.netCtl.getCurrentNetworkInfo()
                self.emit(SIGNAL("refresh_center_net"),num,netAddressList)#发送信号更新中心的可选网络列表
                LogRecord.instance().recordLog(u"发送信号更新中心网络")
                for i in range(num):
                    self.settwIPListRowData(i, netAddressList[i], curNetInfo)
                InfoHintDialog(u"删除成功!").exec_()
                return
        
    def setDynamic(self):
        self.groupBox.setEnabled(False)
    def setStatic(self):
        self.groupBox.setEnabled(True)
        
    def on_pushButtonAddNetaddress_clicked(self):#添加网络
        LogRecord.instance().recordLog(u"点击添加按钮，添加本地网络")
        netAddress = {}
        netCardName = self.netCardComboBox.currentText()
        if (netCardName == ""):
            InfoHintDialog(u"请选择有效网卡！").exec_()
            return
        #判断添加的地址类型
        if(self.adddynamicAddr.isChecked()):#动态地址添加选中
            netAddress["netName"] = "dhcp"
            netAddress["netCard"] = netCardName
            addressType = "dhcp"
        
        elif(self.addstaticAddr.isChecked()):
            netName = self.lineEditNetwork.text().trimmed()
            ip = self.lineEditIpAddr.text().trimmed()
            mask = self.lineEditNetmask.text().trimmed()
            gateway = self.lineEditGateway.text().trimmed()
            dns1 = self.lineEditDnsFirst.text().trimmed()
            dns2 = self.lineEditDnsSecond.text().trimmed()
            
            staticAttribute = ["netName", "ip" , "mask" , "dns1" , "dns2"]
            for i in range(5):
                str = staticAttribute[i]
                self.pushspace(str)
            if(netName == ""):
                InfoHintDialog(u"网络名称不能为空！").exec_()
                return
            if(ip == "" or ip == "..."):
                InfoHintDialog(u"IP地址不能为空！").exec_()
                return
            if(mask == "" or mask == "..."):
                InfoHintDialog(u"子网掩码不能为空！").exec_()
                return
            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, unicode(ip))
            if matchObj is None:
                InfoHintDialog(u'IP地址格式有误，请重新填入').exec_()
                self.lineEditIpAddr.setFocus()
                return

            matchObj = re.match(pattern, unicode(mask))
            if matchObj is None:
                InfoHintDialog(u'子网掩码格式有误，请重新填入').exec_()
                self.lineEditNetmask.setFocus()
                return

            if gateway:
                matchObj = re.match(pattern, unicode(gateway))
                if matchObj is None:
                    InfoHintDialog(u'网关格式有误，请重新填入').exec_()
                    self.lineEditGateway.setFocus()
                    return

            addressType = "static"
            netAddress["netName"] = netName
            netAddress["netIp"] = ip
            netAddress["netMast"] = mask
            netAddress["netGate"] = gateway
            netAddress["netDNS1"] = dns1
            netAddress["netDNS2"] = dns2
            netAddress["netCard"] = netCardName
        
        
        res ,errmsg = self.netCtl.addNetAddress(netAddress,addressType)
        if (not res):
            if errmsg == "dhcpnettoomany":
                InfoHintDialog(u"该网卡已经拥有dhcp网络！").exec_()
                return
            elif errmsg == "netnametoomany":
                InfoHintDialog(u"网络名称已经存在！").exec_()
                return
        else:
            #读取网络地址信息
            LogRecord.instance().recordLog(u"获取文件中的网络列表")
            netAddressList = self.netCtl.getNetAddressList()
            num = len(netAddressList)
            self.twNetwork.setRowCount(num)
            LogRecord.instance().recordLog(u"发送信号更新中心设置中的网络信息")
            self.emit(SIGNAL("refresh_center_net"),num,netAddressList)#更新中心的可用网络列表
            
            if( 0 == num ):
                return
            LogRecord.instance().recordLog(u"获得当前使用网络")
            curNetInfo = self.netCtl.getCurrentNetworkInfo()
            #刷新表格和中心网络中的下拉列表内容
            for i in range(num):
                self.settwIPListRowData(i, netAddressList[i], curNetInfo)
            #清空输入项
            InfoHintDialog(u"添加成功").exec_()
            self.lineEditNetwork.clear()
            self.lineEditIpAddr.clear()
#             self.lineEditNetmask.clear()
            self.lineEditGateway.clear()
            self.lineEditDnsFirst.clear()
            self.lineEditDnsSecond.clear()
            
            self.emit(SIGNAL("updateCenterSetNetCard"))

    
    def pushspace(self,serverip):
        LogRecord.instance().recordLog(u"去空格")
        ipl=serverip.split(" ",QString.SkipEmptyParts)
        serverip=""
        for i in range(len(ipl)):
            serverip+=ipl[i]
        
    def refreshNetCard(self):#更新网卡信息
        LogRecord.instance().recordLog(u"获取网卡列表")
        self.netCardComboBox.clear()
        ethList = self.netCtl.getEthList()
        for i in range(len(ethList)):
            self.netCardComboBox.addItem(ethList[i])
            
    def refreshNetWidget(self):#更新网络列表
        self.lineEditDnsFirst.clear()
        self.lineEditDnsSecond.clear()
        self.lineEditGateway.clear()
        self.lineEditIpAddr.clear()
#         self.lineEditNetmask.clear()
        self.lineEditNetwork.clear()
        LogRecord.instance().recordLog(u"获取文件中的本地网络列表")
        netAddressList = self.netCtl.getNetAddressList()
        num = len(netAddressList)
        self.twNetwork.setRowCount(num)   
        curNetInfo = self.netCtl.getCurrentNetworkInfo()
        for i in range(num): 
            self.settwIPListRowData(i, netAddressList[i], curNetInfo)
    
    def settwIPListRowData(self,row,netAddress,curNetInfo):
        LogRecord.instance().recordLog(u"开始更新表格内容")
        pTWItemNetName = QTableWidgetItem(netAddress["netName"])
        pTWItemNetName.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.twNetwork.setItem(row, 0, pTWItemNetName)
        if (not QString(netAddress["netName"]).startsWith("dhcp")):
            pTWItemNetIp = QTableWidgetItem(netAddress["netIp"])
            pTWItemNetIp.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            self.twNetwork.setItem(row, 1, pTWItemNetIp)
            if (netAddress["netGate"] != "Empty"):
                pTWItemNetGate = QTableWidgetItem(netAddress["netGate"])
                pTWItemNetGate.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
                self.twNetwork.setItem(row, 2, pTWItemNetGate)
        
        
        pTWItemNetCard = QTableWidgetItem(netAddress["netCard"])
        pTWItemNetCard.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.twNetwork.setItem(row, 3, pTWItemNetCard)
    
        pTWItemNetId = QTableWidgetItem(netAddress["addressID"])
        pTWItemNetId.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.twNetwork.setItem(row, 4, pTWItemNetId)
    
        if (curNetInfo == ""):
            pTWItemNetStatus = QTableWidgetItem(u"否")
            pTWItemNetStatus.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            self.twNetwork.setItem(row, 5, pTWItemNetStatus)
            return
        
        status = False
        if (QString(curNetInfo).startsWith("dhcp")):
            if (netAddress["netName"] == curNetInfo.split(":")[0] ):
                status = True
            else:
                status = False
        else:
            infoList = curNetInfo.split(":")
            netname = infoList[0]
            ip = infoList[1]
            id = infoList[2]
            if ((netname == netAddress["netName"]) and (ip == netAddress["netIp"]) and (id == netAddress["addressID"])):
                status = True
            else:
                status = False
        if (status):
            pTWItemNetStatus = QTableWidgetItem(u"是")
            pTWItemNetStatus.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            self.twNetwork.setItem(row, 5, pTWItemNetStatus)
        else:
            pTWItemNetStatus = QTableWidgetItem(u"否")
            pTWItemNetStatus.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            self.twNetwork.setItem(row, 5, pTWItemNetStatus)
        
        
  