#coding=utf-8
from PyQt4.QtGui import QTableWidgetItem,QAbstractItemView,QWidget,QRegExpValidator,QDialog
from PyQt4.QtCore import SIGNAL,QRegExp,QString,Qt,QFile,QIODevice,QTextStream

from common.infohintdialog import InfoHintDialog
from common.messagebox import MessageBox
from view.setting.domainsettings import Ui_Form
from model.setting.hostop import Hostop
from model.cfg.storeinfoparser import StoreInfoParser
from view.setting.domainedit import DomainEditDialog
import re

class DomainSettings(QWidget,Ui_Form):
    def __init__(self):
        super(DomainSettings,self).__init__()
        self.setupUi(self)
        self._Hostop=Hostop()
        self._StoreInfoParser=StoreInfoParser()

        self.tableWidgetList.setColumnWidth(0,280)
        self.tableWidgetList.horizontalHeader().setStretchLastSection(True)
        self.tableWidgetList.setSelectionBehavior(QAbstractItemView.SelectRows)
        
        pReg=QRegExp("[0-9]{0,3}[.][0-9]{0,3}[.][0-9]{0,3}[.][0-9]{0,3}")
        pRegExpValidator2 =QRegExpValidator(pReg)
        self.lineEditIpAddress.setValidator(pRegExpValidator2)
        pReg=QRegExp("[0-9,a-z,.,!,@,#,$,%,^,&,*,:,;,,A-Z,\,/]{0,100}")
        pRegExpValidator2 = QRegExpValidator(pReg)
        self.lineEditDamainName.setValidator(pRegExpValidator2)
        self.tableWidgetList.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setStyleSheet(QString("QLineEdit{border:1px groove rgb(170,214,252);height:25;}"))

        self.updateDomain()
        self.connect(self.pushButtonAdd, SIGNAL("clicked()"),self.addDomain)
        self.connect(self.pushButtonDelete,SIGNAL("clicked()"),self.deleteDomain)
        self.connect(self.pushButtonEdit, SIGNAL("clicked()"),self.editDomain)
        self.pushButtonAdd.setFocus()

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

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

        self._domainEditDialog=DomainEditDialog()
        self._domainEditDialog.lineEditName.setText(self.cenName)
        self._domainEditDialog.lineEditIp.setText(self.cenIP)
        self.connect(self._domainEditDialog,SIGNAL("changeDomainDate"),self.doEditHost)
        self._domainEditDialog.show()

    def keyPressEvent(self,event):
        if(event.key()==Qt.Key_Enter or event.key()==Qt.Key_Return):
            self.pushButtonAdd.setFocus()
            self.addDomain()

    def doEditHost(self,ip,name):
        ip=ip
        name=name
        if( name == "" or ip == "" or ip == "..."):
            self._domainEditDialog.setHidden(True)
            InfoHintDialog(u'名称，中心不得为空！').exec_()
            self._domainEditDialog.show()
            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:
            self._domainEditDialog.setHidden(True)
            InfoHintDialog(u'IP地址格式有误，请重新填入').exec_()
            self._domainEditDialog.show()
            return

        checkR=self._Hostop.checkDaomainL(name)
        if(checkR!=-1):
            if checkR==self.tableWidgetList.currentRow():
                self.deleteDomainHost()
                self.updateDomain()
                self.addDomainHoseEdit(ip,name)
                self._domainEditDialog.close()
                InfoHintDialog(u'编辑成功').exec_()
                return

        checkR=self._Hostop.checkDaomainV(name)
        if(checkR==False):
            self._domainEditDialog.setHidden(True)
            InfoHintDialog(u'该域名已经存在!').exec_()
            self._domainEditDialog.show()
            return

        self.deleteDomainHost()
        self.updateDomain()
        self.addDomainHose(ip,name)
        self._domainEditDialog.close()
        InfoHintDialog(u'编辑成功').exec_()

    def addDomainHoseEdit(self,ip,name):

        self._Hostop.addDomainV(ip,name)
        self.lineEditDamainName.clear()
        self.lineEditIpAddress.clear()
        self.updateDomain()

    def addDomainHose(self,ip,name):
        ip=ip
        name=name
        if( name == "" or ip == "" or ip == "..."):
            InfoHintDialog(u'名称，中心不得为空！').exec_()
            return

        checkR=self._Hostop.checkDaomainV(name)
        if(checkR==False):
            InfoHintDialog(u'该域名已经存在!').exec_()
            return

        self._Hostop.addDomainV(ip,name)
        self.lineEditDamainName.clear()
        self.lineEditIpAddress.clear()
        self.updateDomain()

    def deleteDomain(self):
        itemList = self.tableWidgetList.selectedItems()
        if len(itemList)==0:
            InfoHintDialog(u'请选择需要删除的项！').exec_()
            return

        if (MessageBox(u"确定删除该域名吗？").exec_() == QDialog.Accepted):
            indexTem=[]
            indexTem.append(self.tableWidgetList.currentRow())
            lines = open(self._Hostop.getHostPath()).readlines()
            del lines[self.tableWidgetList.currentRow()]
            open(self._Hostop.getHostPath(),"w").writelines(lines)
            self.updateDomain()
            return

    def deleteDomainHost(self):
        lines = open(self._Hostop.getHostPath()).readlines()
        del lines[self.tableWidgetList.currentRow()]
        open(self._Hostop.getHostPath(),"w").writelines(lines)

    def addDomain(self):
        ip=self.lineEditIpAddress.text().trimmed()
        name=self.lineEditDamainName.text().trimmed()
        if( name == "" or ip == "" or ip == "..."):
            InfoHintDialog(u'IP,主机名不能为空！').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_()
            return

        checkR=self._Hostop.checkDaomainV(name)
        if(checkR==False):
            InfoHintDialog(u'该域名已经存在!').exec_()
            return

        self._Hostop.addDomainV(ip,name)
        self.lineEditDamainName.clear()
        self.lineEditIpAddress.clear()
        self.updateDomain()

    def updateDomain(self):
        hostPath=self._Hostop.getHostPath()
        readv=self._Hostop.readHostFile(hostPath)
        value=self._Hostop.getHostList(readv)
        self.tableWidgetList.setRowCount(len(value))
        for i in range(len(value)):
            pTWItemNetName = QTableWidgetItem(value[i]["ip"])
            pTWItemNetName.setTextAlignment(Qt.AlignCenter)
            self.tableWidgetList.setItem(i,0,pTWItemNetName)

            pTWItemNetIp = QTableWidgetItem(value[i]["name"])
            pTWItemNetIp.setTextAlignment(Qt.AlignCenter)
            self.tableWidgetList.setItem(i,1,pTWItemNetIp)
