#coding:utf-8
'''
Created on Sep 3, 2014

@author: root
'''
import re

from PyQt4.QtCore import SIGNAL, Qt, QString
from PyQt4.QtGui import QComboBox
from PyQt4.QtGui import QGridLayout, QTableWidget, QMenu, QAbstractItemView, QHeaderView, QTableWidgetItem, QCursor, QAction
from PyQt4.QtGui import QGroupBox
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QRadioButton
from PyQt4.QtGui import QWidget, QLabel, QHBoxLayout, QVBoxLayout, QDialog

from base.infohintdialog import InfoHintDialog
from base.messagebox import MessageBox
from setting.getnetinfo import NetCtl
import setting.globalfunc
from setting.logrecord import LogRecord
from setting.netSwitchThread import NetSwitchTd
from setting.waitdlg import WaitingWidget


class WireNetworkSetting(QWidget):
       
    def __init__(self,parent = None):
        super(WireNetworkSetting,self).__init__(parent)
       
        self.netCtl = NetCtl()
        self.netSwitchTd = NetSwitchTd()
        self.waitDlg = WaitingWidget()
        
        self.adddynamicAddr= QRadioButton()
        self.adddynamicAddr.setText(u"添加动态地址")
        
        self.addstaticAddr = QRadioButton()
        self.addstaticAddr.setText(u"添加静态地址")
        
        self.twNetwork = QTableWidget()
        self.twNetwork.setFixedHeight(180)
        
        self.staticSetting = QGroupBox()
        self.staticSetting.setTitle(u"静态地址设置")
        
        self.networkLabel = QLabel(u"网络")
        self.networkLabel.setFixedWidth(80)
        self.ipAddrLabel = QLabel(u"IP地址")
        self.ipAddrLabel.setFixedWidth(80)
        self.netmaskLabel = QLabel(u"子网掩码")
        self.netmaskLabel.setFixedWidth(80)
        self.gatewayLabel = QLabel(u"网关")
        self.gatewayLabel.setFixedWidth(80)
        self.dnsFirstLabel = QLabel(u"DNS1")
        self.dnsFirstLabel.setFixedWidth(80)
        self.dnsSecondLabel = QLabel(u"DNS2")
        self.dnsSecondLabel.setFixedWidth(80)
        self.netCardLabel = QLabel(u"网卡")
        self.netCardLabel.setFixedWidth(80)
        
        self.lineEditNetwork = QLineEdit()
        self.lineEditNetwork.setFixedWidth(300)

        self.lineEditIpAddr = QLineEdit(self)
        self.lineEditIpAddr.setFixedWidth(300)

        self.lineEditNetmask = QLineEdit(self)
        self.lineEditNetmask.setFixedWidth(300)

        self.lineEditGateway = QLineEdit(self)
        self.lineEditGateway.setFixedWidth(300)

        self.lineEditDnsFirst = QLineEdit(self)
        self.lineEditDnsFirst.setFixedWidth(300)

        self.lineEditDnsSecond = QLineEdit(self)
        self.lineEditDnsSecond.setFixedWidth(300)

        self.netCardComboBox = QComboBox()
        self.netCardComboBox.setFixedWidth(300)
        
        self.startButton = QPushButton(u"启用")
        self.startButton.setObjectName("settingDlgBtn")
        self.startButton.setFixedSize(75,27)
        self.startButton.setFlat(True)
        self.deleteButton = QPushButton(u"删除")
        self.deleteButton.setObjectName("settingDlgBtn")
        self.deleteButton.setFixedSize(75,27)
        self.deleteButton.setFlat(True)
        self.addButton = QPushButton(u"添加")
        self.addButton.setObjectName("settingDlgBtn")
        self.addButton.setFixedSize(75,27)
        self.addButton.setFlat(True)
        self.closeButton = QPushButton(u"关闭")
        self.closeButton.setObjectName("settingDlgBtn")
        self.closeButton.setFixedSize(75,27)
        self.closeButton.setFlat(True)
        
        groupLayout = QGridLayout()
        groupLayout.addWidget(self.networkLabel,0,0)
        groupLayout.addWidget(self.lineEditNetwork,0,1)
        groupLayout.addWidget(self.ipAddrLabel,1,0)
        groupLayout.addWidget(self.lineEditIpAddr,1,1)
        groupLayout.addWidget(self.netmaskLabel,2,0)
        groupLayout.addWidget(self.lineEditNetmask,2,1)
        groupLayout.addWidget(self.gatewayLabel,3,0)
        groupLayout.addWidget(self.lineEditGateway,3,1)
        groupLayout.addWidget(self.dnsFirstLabel,4,0)
        groupLayout.addWidget(self.lineEditDnsFirst,4,1)
        groupLayout.addWidget(self.dnsSecondLabel,5,0)
        groupLayout.addWidget(self.lineEditDnsSecond,5,1)
        groupLayout.addWidget(self.netCardLabel,6,0)
        groupLayout.addWidget(self.netCardComboBox,6,1)
        groupLayout.addWidget(self.addButton,6,2)
        
        addLayout = QHBoxLayout()
        addLayout.addStretch()
        addLayout.addWidget(self.addButton)
        
        mLayout = QHBoxLayout()
        mLayout.addSpacing(30)
        mLayout.addLayout(groupLayout)
        
        gLayout = QVBoxLayout()
        gLayout.addLayout(mLayout)
        
        self.staticSetting.setLayout(gLayout)
        
        addButtonLayout = QHBoxLayout()
        addButtonLayout.addWidget(self.addstaticAddr)
        addButtonLayout.addWidget(self.adddynamicAddr)
        addButtonLayout.addStretch()
        addButtonLayout.addWidget(self.startButton)
        addButtonLayout.addWidget(self.deleteButton)
        
        closeButtonLayout = QHBoxLayout()
        closeButtonLayout.addStretch()
        closeButtonLayout.addWidget(self.closeButton)
        
        miniWidget = QWidget()
        vLayout = QVBoxLayout()
        vLayout.setMargin(0)
        vLayout.addWidget(self.twNetwork)
        vLayout.addLayout(addButtonLayout)
        vLayout.addWidget(self.staticSetting)
        vLayout.addLayout(closeButtonLayout)
        miniWidget.setLayout(vLayout)
        
        self.mainLayout = QHBoxLayout(self)
        self.mainLayout.addSpacing(30)
        self.mainLayout.addWidget(miniWidget)
        self.mainLayout.addSpacing(30)
        
        self.ipTabelMenu = QMenu(self.twNetwork)
        self.delIpAction = QAction(u"删除", self)
        self.startAction = QAction(u"启用", self)
        self.connect(self.delIpAction, SIGNAL("triggered()"), self.deleteIPAddress)
        self.connect(self.startAction, SIGNAL("triggered()"),self.on_pushButtonNetworkStart_clicked)
        
        
        self.refreshNetCard()
            
        self.headList = [u"网络",u"IP地址",u"网关",u"网卡",u"ID",u"是否启用"]
        self.twNetwork.clear()
        self.twNetwork.setColumnCount(6)
        self.twNetwork.hideColumn(4)
        self.twNetwork.setAlternatingRowColors(1)
        self.twNetwork.setHorizontalHeaderLabels(self.headList)
        self.twNetwork.horizontalHeader().setResizeMode(QHeaderView.Stretch)
  
        self.twNetwork.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.twNetwork.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.twNetwork.setSelectionMode(QAbstractItemView.SingleSelection)
        self.twNetwork.setContextMenuPolicy(Qt.CustomContextMenu)
        self.twNetwork.customContextMenuRequested.connect(self.on_twIPList_customContextMenuRequested)
        headerView = self.twNetwork.verticalHeader()
        headerView.setHidden(True)
        
        self.initCurrentNet()
        LogRecord.instance().logger.info(u"更新表格内容")
        self.refreshNetWidget()
        self.addstaticAddr.setChecked(True)
        
        self.connect(self.addstaticAddr, SIGNAL("clicked()"),self.setStatic)
        self.connect(self.adddynamicAddr, SIGNAL("clicked()"),self.setDynamic)
        
        self.connect(self.closeButton, SIGNAL("clicked()"),self.closeTabWidget)
        self.connect(self.deleteButton,SIGNAL("clicked()"),self.on_pushButtonNetworkDel_clicked)
        self.connect(self.addButton, SIGNAL("clicked()"),self.on_pushButtonAddNetaddress_clicked)
        self.connect(self.twNetwork, SIGNAL("clicked()"),self.on_twIPList_customContextMenuRequested)
        self.connect(self.startButton, SIGNAL("clicked()"),self.on_pushButtonNetworkStart_clicked)
        
        self.connect(self.netSwitchTd, SIGNAL("networkSwitchSignal"),self.exception)
        self.connect(self.netSwitchTd, SIGNAL("addNetworkItemSignal"),self.exception)
        self.connect(self.netSwitchTd, SIGNAL("authCertificateSignal"),self.exception)
        self.connect(self.netSwitchTd, SIGNAL("restartNetworkSignal"),self.showRestartNetworkInfo)
    def initCurrentNet(self):
        pass
    def refreshNetCard(self):
        LogRecord.instance().logger.info(u"获取网卡列表")
        self.netCardComboBox.clear()
        ethList = self.netCtl.getEthList()
        for i in range(len(ethList)):
            self.netCardComboBox.addItem(ethList[i])
        
    def setStatic(self):
        LogRecord.instance().logger.info(u"点击静态地址")
        self.staticSetting.setEnabled(True)
        self.lineEditNetwork.setEnabled(True)
        self.lineEditIpAddr.setEnabled(True)
        self.lineEditNetmask.setEnabled(True)
        self.lineEditGateway.setEnabled(True)
        self.lineEditDnsFirst.setEnabled(True)
        self.lineEditDnsSecond.setEnabled(True)
    def setDynamic(self):
        LogRecord.instance().logger.info(u"点击动态地址")
        self.lineEditNetwork.setEnabled(False)
        self.lineEditIpAddr.setEnabled(False)
        self.lineEditNetmask.setEnabled(False)
        self.lineEditGateway.setEnabled(False)
        self.lineEditDnsFirst.setEnabled(False)
        self.lineEditDnsSecond.setEnabled(False)
        
    def showRestartNetworkInfo(self,result):
        if (result == 0):
            #waitDlg->setText(tr("网络启动成功!"));
         
            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):
            #waitDlg->setText(tr("正在重新启动网络服务，请稍后......"))
            #waitDlg->show()
            #print "正在重新启动网络服务，请稍后......"
            return
        
        elif (result == -1):
            self.waitDlg.close()
            InfoHintDialog(u"网络重启失败！").exec_()
            return
        else:
            self.waitDlg.close()
            InfoHintDialog(u"网络重启失败！").exec_()
            return
    def exception(self):
        pass
    def refreshNetWidget(self):
        #self.twNetwork.clear()
        self.lineEditDnsFirst.clear()
        self.lineEditDnsSecond.clear()
        self.lineEditGateway.clear()
        self.lineEditIpAddr.clear()
        self.lineEditNetmask.clear()
        self.lineEditNetwork.clear()
        LogRecord.instance().logger.info(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 closeTabWidget(self):
        LogRecord.instance().logger.info(u"关闭按钮信号")
        self.emit(SIGNAL("closetabwidget"))    
           
    def settwIPListRowData(self,row,netAddress,curNetInfo):
        LogRecord.instance().logger.info(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)
        
    
    
    
    def pushspace(self,serverip):
        LogRecord.instance().logger.info(u"去空格")
        ipl=serverip.split(" ",QString.SkipEmptyParts)
        serverip=""
        for i in range(len(ipl)):
            serverip+=ipl[i]

    def on_pushButtonAddNetaddress_clicked(self):#添加网络

        
        LogRecord.instance().logger.info(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()
            

                
            
            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().logger.info(u"获取文件中的网络列表")
            netAddressList = self.netCtl.getNetAddressList()
            num = len(netAddressList)
            self.twNetwork.setRowCount(num)
            LogRecord.instance().logger.info(u"发送信号更新平台设置中的网络信息")
            self.emit(SIGNAL("refresh_center_net"),num,netAddressList)#更新平台的可用网络列表
            
            if( 0 == num ):
                return
            #得到当前的网络信息
            LogRecord.instance().logger.info(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()

    
    def on_pushButtonNetworkDel_clicked(self):#删除网络
        LogRecord.instance().logger.info(u"点击删除网络按钮")
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u"请选择相应的网络！").exec_()
            return
        LogRecord.instance().logger.info(u"删除网络")
        self.deleteIPAddress()

    def on_pushButtonNetworkStart_clicked(self):#启用某个网络
        LogRecord.instance().logger.info(u"点击启用")
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u"请选择相应的网络！").exec_()
            return
        #获取当前网络的信息
        currentRow = self.twNetwork.currentRow()
        item = self.twNetwork.item(currentRow, 4)
        if (item != ""):
            addressID = item.text()
            #print addressID
            #重启网络
            self.netSwitchTd.setNetID(addressID)
            self.netSwitchTd.setFunType("RESTART_NET_SERVERS")
            LogRecord.instance().logger.info(u"启动重启网络的线程")
            self.netSwitchTd.start()
            self.waitDlg.setTip(u"重启网络中...")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
    def deleteIPAddress(self):
        if(MessageBox(u"确定删除该网络吗?").exec_() == QDialog.Rejected):
            return
        
        currentRow = self.twNetwork.currentRow()
        item = self.twNetwork.item(currentRow, 4)
        if (item != ""):
            addressID = item.text()
            LogRecord.instance().logger.info(u"进入getnetinfo的delNetAddressItem函数")
            result = self.netCtl.delNetAddressItem(addressID)
            if (result == -1):
                InfoHintDialog(u"删除网络失败!").exec_()
                return
            elif (result == -2):
                InfoHintDialog(u"正被使用中!").exec_()
                return
            elif (result == -3):
                InfoHintDialog(u"该网络已被平台使用!").exec_()
                return
            else:
                #刷新表格内容
                LogRecord.instance().logger.info(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().logger.info(u"获取当前网络")
                curNetInfo = self.netCtl.getCurrentNetworkInfo()
                self.emit(SIGNAL("refresh_center_net"),num,netAddressList)#发送信号更新平台的可选网络列表
                LogRecord.instance().logger.info(u"发送信号更新平台网络")
                #刷新表格和平台网络中的下拉列表内容
                for i in range(num):
                    self.settwIPListRowData(i, netAddressList[i], curNetInfo)
                InfoHintDialog(u"删除成功!").exec_()
                return
        
    def on_twIPList_customContextMenuRequested(self,pos):
        LogRecord.instance().logger.info(u"右键菜单")
        item = self.twNetwork.itemAt(pos)
        if (item != None):
            self.ipTabelMenu.clear()
            self.ipTabelMenu.addAction(self.delIpAction)
            self.ipTabelMenu.addAction(self.startAction)
            self.ipTabelMenu.exec_(QCursor.pos())

if __name__ == "__main__":
    from PyQt4 import QtGui
    app = QtGui.QApplication([])
    wireNet = WireNetworkSetting()
    wireNet.show()
    app.exec_()
    #pass