#coding=utf-8
from PyQt4.QtGui import QTableWidgetItem,QAbstractItemView,QDialog,QRegExpValidator,QIntValidator
from PyQt4.QtCore import Qt,QString,SIGNAL,QRegExp
from view.setting.centerset import Ui_Form
# from model.setting.base.infohintdialog import InfoHintDialog
from common.infohintdialog import InfoHintDialog
from model.setting.getnetinfo import NetCtl
from model.setting.centerapi import CenterApi
# from model.setting.base.messagebox import MessageBox
from common.messagebox import MessageBox
from view.setting.centeredit import CenterEditDialog
from common.logrecord import LogRecord
import model.setting
import re
from PyQt4.Qt import QWidget
 
class CenterSet(QWidget,Ui_Form):
    def __init__(self):
        super(CenterSet,self).__init__()
        #--------------界面初始化-top
        self.setupUi(self)
        self.twNetwork.horizontalHeader().setStretchLastSection(True)
        self.twNetwork.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.twNetwork.setColumnWidth(0,160)
        self.twNetwork.setColumnWidth(1,160)
        self.twNetwork.setColumnWidth(2,140)
        self.twNetwork.setColumnWidth(3,126)
        self.twNetwork.hideColumn(2)
        self.label_4.setHidden(True)
        self.lineEditPort.setHidden(True)
        self.twNetwork.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setStyleSheet(QString("QLineEdit{border:1px groove rgb(170,214,252);height:25;}"))
        self.netComboBox.setStyleSheet(QString("border:1px groove rgb(170,214,252);height:25;"))
        
        pReg=QRegExp("[0-9]{0,3}[.][0-9]{0,3}[.][0-9]{0,3}[.][0-9]{0,3}")
        pRegExpValidator2 = QRegExpValidator(pReg)
        self.lineEditCentre.setValidator(pRegExpValidator2)
        self.lineEditPort.setValidator(QIntValidator(0,65535))
        
        self.netCtl=NetCtl()# -p
        self.centerApi=CenterApi()# -p
        self.editDlg = CenterEditDialog()#-p

        self.refreshComboNet()#获取网卡更新
        self.refreshNetworkTable()#列表更新
        self.refreshAutoNet()#检测是否点击自动获取中心
        self.connect(self.editDlg, SIGNAL("updateCenter_Date"),self.updateCent)
        self.connect(self.pushButtonAdd, SIGNAL("clicked()"),self.onPushButtonAddClicked)
        self.connect(self.pushButtonDelete, SIGNAL("clicked()"),self.onPushButtonDeleteClicked)
        self.connect(self.cbNetworkAuto,SIGNAL("toggled(bool)"),self.onCbnetworkautoClicked)
        self.connect(self.pushButtonEdit,SIGNAL("clicked()"),self.editNetWork)
        self.cbNetworkAuto.setHidden(True)
        
    def updateCent(self):
        self.emit(SIGNAL("updateCenter_Date"))
        
    def editNetWork(self):
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u"请选择相应的中心！").exec_()
            return
        
        currentRow = self.twNetwork.currentRow()
        netNameItem = self.twNetwork.item(currentRow, 0)
        netName = netNameItem.text()
        netIPItem = self.twNetwork.item(currentRow, 1)
        netIP = netIPItem.text()
        netLocalItem = self.twNetwork.item(currentRow, 3)
        netLocal = netLocalItem.text()
    
        centerEditItem = {}
        centerEditItem["netName"] = netName
        centerEditItem["netIp"] = netIP
        centerEditItem["netLocal"] = netLocal
    
        self.editDlg.setCenterInfo(centerEditItem)
        self.editDlg.show()
        self.connect(self.editDlg, SIGNAL("updateCenter_Date"),self.refreshNetworkTable)
        self.editDlg.move(model.setting.globalfunc.moveToCenter(self.editDlg.width(), self.editDlg.height()))
        
        
    def refreshAutoNet(self):
        pass
        
    def onCbnetworkautoClicked(self,auto):
        if(auto):
            self.pushButtonEdit.setEnabled(False)
            self.pushButtonDelete.setEnabled(False)
            self.twNetwork.setEnabled(False)
            s="true"
        else:
            self.pushButtonEdit.setEnabled(True)
            self.pushButtonDelete.setEnabled(True)
            self.twNetwork.setEnabled(True)
            s="false"
        
    def onPushButtonDeleteClicked(self):
        LogRecord.instance().recordLog(u"点击删除按钮")
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u"请选择相应的中心！").exec_()
            return
        LogRecord.instance().recordLog(u"进入自身函数deleteNetwork")
        self.deleteNetwork()
        self.refreshNetworkTable()
        self.emit(SIGNAL("updateCenter_Date"))
    def deleteNetwork(self):
        if (MessageBox(u"确定删除该中心吗?").exec_() == QDialog.Rejected):
            return
        currentRow = self.twNetwork.currentRow()
        centerName = QTableWidgetItem(self.twNetwork.item(currentRow,0)).text()
        LogRecord.instance().recordLog(u"删除中心")
        result = self.centerApi.delNetWorkSwitchItem(centerName)
        if (result == -1):
            InfoHintDialog(u"删除网络失败!").exec_()
            return
        elif (result == -4):
            InfoHintDialog(u"打开中心配置文件失败!").exec_()
            return

    def refreshNetworkTable(self):
        LogRecord.instance().recordLog(u"更新中心的列表的界面化显示，开始获取中心列表")
        netSwitchlist = self.centerApi.getNetSwitchList()
        if netSwitchlist < 0 :
            LogRecord.instance().recordLog(u"获取中心列表为空")
            num = 0
        else:
            num = len(netSwitchlist)
        if( 0 == num ):
            self.twNetwork.setRowCount(num)
            return
        self.twNetwork.setRowCount(num)
        LogRecord.instance().recordLog(u"开始将列表显示在表格中")
        for i in range(num):
            self.settwNetWorkRowData(i,netSwitchlist[i])
            
    def settwNetWorkRowData(self,row,netSwitch):
        pTWItemNetName = QTableWidgetItem(netSwitch["netName"])
        pTWItemNetName.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 0, pTWItemNetName)
    
        pTWItemNetIp = QTableWidgetItem(netSwitch["netIp"])
        pTWItemNetIp.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 1, pTWItemNetIp)
    
        pTWItemNetPort = QTableWidgetItem(netSwitch["netPort"])
        pTWItemNetPort.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 2, pTWItemNetPort)
    
        pTWItemNetWorkName = QTableWidgetItem(netSwitch["networkName"])
        pTWItemNetWorkName.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 3, pTWItemNetWorkName)


    def onPushButtonAddClicked(self):
        LogRecord.instance().recordLog(u"点击添加按钮")
        #判断输入的信息是否有效
        centerName = self.lineEditName.text().trimmed()
        netSwitchlist = self.centerApi.getNetSwitchList()
        for i in range(len(netSwitchlist)):
            if(netSwitchlist[i]["netName"]==centerName):
                InfoHintDialog(u"已有该中心名称").exec_()
                return
        centerIp = self.lineEditCentre.text().trimmed()
        centerPort = self.lineEditPort.text().trimmed()
        centerNetWork = self.netComboBox.currentText()
        centerNetSwitch = "None"
    
        if (centerNetWork == ""):
            InfoHintDialog(u"请选择或配置相应的网络!").exec_()
            return
        curIndex = int(self.netComboBox.currentIndex())
        netId = self.netComboBox.itemData(curIndex, Qt.UserRole + 1).toString()
    
        #ip去空格
        ipl=centerIp.split(" ",QString.SkipEmptyParts)
        centerIp=""
        for i in range(len(ipl)):
            centerIp=centerIp+ipl[i]
        #端口去空格
        centerPort="None"
        pol=centerPort.split(" ",QString.SkipEmptyParts)
        centerPort=""
        for i in range(len(pol)):
            centerPort=centerPort+pol[i]
        
        if( centerName == "" or centerPort == "" or centerIp == "" or centerIp == "..."):
            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(centerIp))
        if matchObj is None:
            InfoHintDialog(u'IP地址格式有误，请重新填入').exec_()
            return
        
        ssl="false"
        info = {}
        info["netName"] = centerName
        info["netIp"] = centerIp
        info["netPort"] = centerPort
        info["netSsl"] = ssl
        info["netId"] = netId
        info["networkName"] = centerNetWork
        info["netSwitch"] = centerNetSwitch
        
        result =self.centerApi.setNetworkSwitch(centerName, centerIp, centerPort,centerNetWork)#填入中心配置文件
        self.refreshNetworkTable()
        self.lineEditCentre.clear()
        self.lineEditName.clear()
        self.lineEditPort.clear()
        
        self.emit(SIGNAL("updateCenter_Date"))


    def refreshComboNet(self):#获取本地网络列表
        LogRecord.instance().recordLog(u"开始获取本地网络列表，并且将这个列表显示在combo框中，进入getnetinfo的getNetAddressList函数")
        netAddressList = self.netCtl.getNetAddressList()
        num = len(netAddressList)
        LogRecord.instance().recordLog(u"获得当前使用的本地网络，进入函数getnetinfo的getCurrentNetworkInfo")
        curNetInfo = self.netCtl.getCurrentNetworkInfo()
        self.netComboBox.clear()      
        index = -1
        #刷新表格内容
        for i in range(num):
            if (not curNetInfo == ""):
                netName = netAddressList[i]["netName"]
                if (netName == curNetInfo.split(":")[0]):
                    index = i
    
            self.netComboBox.addItem(netAddressList[i]["netName"])
            self.netComboBox.setItemData(i, netAddressList[i]["addressID"], Qt.UserRole + 1)
    
        self.netComboBox.setCurrentIndex(index)

        
        