#coding=utf-8
from PyQt4.QtGui import QTableWidgetItem,QAbstractItemView,QDialog,QWidget,QRegExpValidator
from view.setting.domainsettings import Ui_Form
from PyQt4.QtCore import SIGNAL,QRegExp,QString

from common.logrecord import LogRecord
# from model.setting.base.messagebox import MessageBox
from common.messagebox import MessageBox
from model.setting.hostop import Hostop
from view.setting.editdlg import EditDialog
from common.globalfun import moveWidgetToScreenCenter
from common.infohintdialog import InfoHintDialog
import re

 
class DomainSettings(QWidget,Ui_Form):
    def __init__(self):
        super(DomainSettings,self).__init__()
        self.setupUi(self)
        self.tableWidgetList.setColumnWidth(0,280)
        self.tableWidgetList.horizontalHeader().setStretchLastSection(True)
        self.tableWidgetList.setSelectionBehavior(QAbstractItemView.SelectRows)
        
        self.hostop = Hostop()
        self.updateDomain()
        self.editDlg = EditDialog()
        
        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)
        
        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.connect(self.editDlg, SIGNAL("edithostover"),self.editHost)
        self.tableWidgetList.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setStyleSheet(QString("QLineEdit{border:1px groove rgb(170,214,252);height:25;}"))
        
    def checkDaomainL(self,name):
        list=self.hostop.getHostList()
        for i in range(len(list)):
            if(len(list[i])>1):
                if(list[i]["hostdes"]==name):
                    return i
        return -1
    
    def checkDaomainV(self,name):
        list=self.hostop.getHostList()
        for i in range(len(list)):
            if(len(list[i])>1):
                if(list[i]["hostdes"]==name):
                    return False
        return True
    
    def editHost(self,name,ip):
        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.editDlg.setHidden(True)
            InfoHintDialog(u'IP地址格式有误，请重新填入').exec_()
            self.editDlg.setHidden(False)
            return
        if(name == ""):
            self.editDlg.setHidden(True)
            InfoHintDialog(u'用户名不能为空！').exec_()
            self.editDlg.setHidden(False)
            return
        
        checkR=self.checkDaomainL(name)
        if(checkR!=-1):
            if checkR==self.tableWidgetList.currentRow():
                itemList = {}
                itemList["hostdes"] = name
                itemList["hostip"] = ip
#                 if not self.hostop.checkItemValid(itemList):
#                     self.editDlg.close()
#                     InfoHintDialog(u"当前域名已经存在").exec_()
#                     return
                currentRow = self.tableWidgetList.currentRow()
                netIpItem = self.tableWidgetList.item(currentRow, 0)
                currentIp = netIpItem.text()
                netNameItem = self.tableWidgetList.item(currentRow, 1)
                currentName = netNameItem.text()
                deleteItem = {}
                deleteItem["hostip"] = currentIp
                deleteItem["hostdes"] = currentName
                deleteList = []
                deleteList.append(deleteItem)
                self.hostop.deleHostCont(deleteList)
                
                hostList = {}
                hostList["hostip"] = ip
                hostList["hostdes"] = name
                self.hostop.writeHostFile(hostList)
                self.updateDomain()
                self.editDlg.close()
                InfoHintDialog(u"域名修改成功").exec_()
                return
        
        checkR=self.checkDaomainV(name)
        if(checkR==False):
            self.editDlg.setHidden(True)
            InfoHintDialog(u'该域名已经存在!').exec_()
            self.editDlg.show()
            return
        
        
        
        itemList = {}
        itemList["hostdes"] = name
        itemList["hostip"] = ip
        if not self.hostop.checkItemValid(itemList):
            self.editDlg.close()
            InfoHintDialog(u"当前域名已经存在").exec_()
            return
        currentRow = self.tableWidgetList.currentRow()
        netIpItem = self.tableWidgetList.item(currentRow, 0)
        currentIp = netIpItem.text()
        netNameItem = self.tableWidgetList.item(currentRow, 1)
        currentName = netNameItem.text()
        deleteItem = {}
        deleteItem["hostip"] = currentIp
        deleteItem["hostdes"] = currentName
        deleteList = []
        deleteList.append(deleteItem)
        self.hostop.deleHostCont(deleteList)
        
        hostList = {}
        hostList["hostip"] = ip
        hostList["hostdes"] = name
        self.hostop.writeHostFile(hostList)
        self.updateDomain()
        self.editDlg.close()
        InfoHintDialog(u"域名修改成功").exec_()
        
    def editDomain(self):
        LogRecord.instance().recordLog(u"点击编辑按钮")
        itemList = self.tableWidgetList.selectedItems()
        if len(itemList) == 0 :
            InfoHintDialog(u"请先选择某一个要编辑的域").exec_()
            return
        if len(itemList) >2:
            InfoHintDialog(u"请选择一处进行编辑").exec_()
            return
        hostip = itemList[0].text()
        hostname = itemList[1].text()
        info = {}
        info["hostip"] = hostip
        info["hostdes"] = hostname
        delist = []
        delist.append(info)
        self.editDlg.show()
        self.editDlg.setHostInfo(info)
        self.connect(self.editDlg, SIGNAL("errorinputip"),self.errorMessIp)
    def errorMessIp(self):
        self.editDlg.setHidden(True)
        _InfoTemp=InfoHintDialog(u"IP地址输入错误！").exec_()
        self.editDlg.show()

    def deleteDomain(self):
        LogRecord.instance().recordLog(u"删除域名按钮")
        itemList = self.tableWidgetList.selectedItems()
        if len(itemList)==0:
            InfoHintDialog(u"请先选择要删除的域").exec_()
            return
        if MessageBox(u"确定删除该域名吗?").exec_() == QDialog.Rejected :
            return
        
        deleHostList = []
        for i in range(len(itemList)):
            hostlist = {}
            if itemList[i].column()==1:
                hostip = itemList[0].text()
                hostname = itemList[1].text()
                hostlist["hostip"] = hostip
                hostlist["hostdes"] = hostname
                deleHostList.append(hostlist)

        LogRecord.instance().recordLog(u"删除选中行")
        if 0 != self.hostop.deleHostCont(deleHostList):
            InfoHintDialog(u"删除相应的域名失败").exec_()
        
        LogRecord.instance().recordLog(u"得到文件中的主机列表，并且更新在表格中")
        self.updateDomain()
    
    def updateDomain(self):#刷新域名显示界面
        hostList = self.hostop.getHostList()
        num = len(hostList)
        self.tableWidgetList.setRowCount(num)
        
        for i in range(num):          
            item0=QTableWidgetItem(hostList[i]["hostip"])
            item1=QTableWidgetItem(hostList[i]["hostdes"])
            self.tableWidgetList.setItem(i,0,item0)
            self.tableWidgetList.setItem(i,1,item1)
            
    def addDomain(self):#域名添加功能
        ip=self.lineEditIpAddress.text().trimmed()
        hostName=self.lineEditDamainName.text().trimmed()        
        LogRecord.instance().recordLog(u"添加按钮点击")
        if (ip == "" or ip == "..." or hostName == ""):
            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
        
        itemList = {}
        itemList["hostdes"] = hostName
        itemList["hostip"] = ip
        if not self.hostop.checkItemValid(itemList):
            #QMessageBox.information(self,u"信息",u"当前域名已经存在")
            InfoHintDialog(u"当前域名已经存在").exec_()
            return
        self.hostop.writeHostFile(itemList)
        
        self.lineEditIpAddress.clear()
        self.lineEditDamainName.setText("")
        self.lineEditIpAddress.setFocus()
        self.updateDomain()
        

        
        
        
        
        
        
        
        
        
        