#coding:utf-8
import json, re

from PyQt4.QtGui import QTableWidgetItem,QAbstractItemView,QRegExpValidator,QIntValidator,QDialog
from PyQt4.QtCore import Qt,QString,SIGNAL,QRegExp
from PyQt4.Qt import QWidget

from common.infohintdialog import InfoHintDialog
from common.messagebox import MessageBox
from view.setting.centerset import Ui_Form
from model.cfg.storeinfoparser import StoreInfoParser
from view.setting.centeredit import CenterEditDialog

class CenterSet(QWidget,Ui_Form):
    def __init__(self):
        super(CenterSet,self).__init__()
        #--------------界面初始化-top
        self.setupUi(self)
        self.twNetwork.horizontalHeader().setStretchLastSection(True)
        self.twNetwork.setColumnWidth(0,250)
        self.twNetwork.setColumnWidth(1,160)

        self.twNetwork.hideColumn(2)
        self.twNetwork.hideColumn(3)
        self.label_4.setHidden(True)
        self.label_5.setHidden(True)
        self.lineEditPort.setHidden(True)
        self.netComboBox.setHidden(True)
        self.cbNetworkAuto.setHidden(True)
        self.twNetwork.setSelectionMode(QAbstractItemView.SingleSelection)
        self.twNetwork.setSelectionBehavior(QAbstractItemView.SelectRows)
        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.cenName = QString("")
        self.cenIP = QString("")
        self._StoreInfoParser=StoreInfoParser()
        self.updateCent()
        self.connect(self.pushButtonAdd,SIGNAL("clicked()"),self.onPushButtonAddClicked)
        self.connect(self.pushButtonDelete, SIGNAL("clicked()"),self.onPushButtonDeleteClicked)
        self.connect(self.pushButtonEdit,SIGNAL("clicked()"),self.editCenter)

    def editCenter(self):
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u'请选择相应的中心！').exec_()
            return

        currentRow = self.twNetwork.currentRow()
        netNameItem = self.twNetwork.item(currentRow, 0)
        self.cenName = netNameItem.text()
        netIPItem = self.twNetwork.item(currentRow, 1)
        self.cenIP = netIPItem.text()

        self._centerEditDialog=CenterEditDialog()
        self._centerEditDialog.show()
        self._centerEditDialog.lineEditName.setText(self.cenName)
        self._centerEditDialog.lineEditIp.setText(self.cenIP)

        self.connect(self._centerEditDialog,SIGNAL("changeCenterDate"),self.doEditCenter)

    def doEditCenter(self,name,ip):
        getv=self._StoreInfoParser.getConfigFileValue("networkswitch")
        tempv=json.loads(getv)
        for i in tempv:
            if (i == name):
                self._centerEditDialog.close()
                InfoHintDialog(u'已经存在该中心名称').exec_()
                return
        for i in tempv:
            if(i == self.cenName):
                tempv.pop(i)
                tempList={}
                tempList["networkName"]=str(unicode(name, "utf-8"))
                tempList["centerIp"]=str(ip)
                tempv[str(unicode(name, "utf-8"))]=tempList
                self._StoreInfoParser.setConfigFileValue("networkswitch",json.dumps(tempv, ensure_ascii=False))
                break
        self.updateCent()
        self._centerEditDialog.close()
        self.emit(SIGNAL("updateCenter_Date"))
        InfoHintDialog(u'编辑成功！').exec_()

    def onPushButtonDeleteClicked(self):
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u'请选择相应的中心！').exec_()
            return
        if (MessageBox(u"确定删除该中心吗？").exec_() == QDialog.Accepted):
            currentRow = self.twNetwork.currentRow()
            centerName = QTableWidgetItem(self.twNetwork.item(currentRow,0)).text()
            getv=self._StoreInfoParser.getConfigFileValue("networkswitch")
            tempv=json.loads(getv)
            for i in tempv:
                if(i==str(centerName)):
                    tempv.pop(i)
                    break
            self._StoreInfoParser.setConfigFileValue("networkswitch",json.dumps(tempv, ensure_ascii=False))
            self.updateCent()
            self.emit(SIGNAL("updateCenter_Date"))
        else:
            return

    def onPushButtonAddClicked(self):
        centerName = self.lineEditName.text().trimmed()
        centerIp = self.lineEditCentre.text().trimmed()
        if( centerName == "" 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

        tempList={}
        tempList["networkName"]=str(unicode(centerName, "utf-8"))
        tempList["centerIp"]=str(centerIp)

        getv=self._StoreInfoParser.instance().getConfigFileValue("networkswitch")
        if(getv!=""):
            tempv=json.loads(getv)
            for i in tempv:
                if(i == centerName):
                    InfoHintDialog(u'已存在该中心！').exec_()
                    return
        else:
            tempv={}
        tempv[str(unicode(centerName, "utf-8"))]=tempList
        self._StoreInfoParser.setConfigFileValue("networkswitch",json.dumps(tempv,ensure_ascii=False))
        self.lineEditCentre.clear()
        self.lineEditName.clear()
        self.updateCent()

        self.emit(SIGNAL("updateCenter_Date"))

    def updateCent(self):
        tempv=StoreInfoParser.instance().getConfigFileValue("networkswitch")
        if(tempv==""):
            return
        else:
            tempList=json.loads(tempv)
            temprow=0
            netSwitchList=[]
            for i in tempList:
                subNetList = {}
                subNetList["networkName"]=tempList[i]["networkName"]
                subNetList["centerIp"] = tempList[i]["centerIp"]
                netSwitchList.append(subNetList)
            self.twNetwork.setRowCount(len(netSwitchList))
            for i in range(len(netSwitchList)):
                pTWItemNetName = QTableWidgetItem(netSwitchList[i]["networkName"])
                pTWItemNetName.setTextAlignment(Qt.AlignCenter)
                self.twNetwork.setItem(temprow, 0, pTWItemNetName)

                pTWItemNetIp = QTableWidgetItem(netSwitchList[i]["centerIp"])
                pTWItemNetIp.setTextAlignment(Qt.AlignCenter)
                self.twNetwork.setItem(temprow, 1, pTWItemNetIp)
                temprow=temprow+1
