#coding:utf-8
'''
Created on Sep 3, 2014
@author: root
'''
import re

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

from base.infohintdialog import InfoHintDialog
from base.messagebox import MessageBox
from setting.centerapi import CenterApi
from setting.editdlg import EditDialog
import setting.globalfunc
from setting.hostop import Hostop
from setting.logrecord import LogRecord


class DominMapSetting(QWidget):
    def __init__(self,parent = None):
        super(DominMapSetting,self).__init__(parent)
      
        self.hostop = Hostop()
        self.centerApi = CenterApi()
        self.editDlg = EditDialog()
        
        self.tabView = QTableWidget()
        self.tabView.setColumnCount(2)
        strList = [u"IP地址",u"主机名"]
        self.tabView.setHorizontalHeaderLabels(strList)
  
        self.tabView.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        self.tabView.setSelectionBehavior(QAbstractItemView.SelectRows)  #整行选中的方式
        self.tabView.setAlternatingRowColors(1)
        self.tabView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tabView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tabView.customContextMenuRequested.connect(self.on_tableWidgetHost_customContextMenuRequested)
        self.connect(self.tabView,SIGNAL("itemClicked(QTableWidgetItem*)"),self.slotRead)
        
        headerView = self.tabView.verticalHeader()
        headerView.setHidden(True)
        horizonHeaderView = self.tabView.horizontalHeader()
        horizonHeaderView.setStyleSheet("background-color: rgb(235, 235, 235);")
        
        self.hostTableMenu = QMenu(self.tabView)
        self.delHostAction = QAction(u"删 除", self)
        self.editHostAction = QAction(u"编 辑", self)
        self.connect(self.delHostAction, SIGNAL("triggered()"), self.on_pushButtonDeleHost_clicked)
        self.connect(self.editHostAction, SIGNAL("triggered()"), self.editAction)

        
       
        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.editButton = QPushButton(u"编辑")
        self.editButton.setFixedSize(75,27)
        self.editButton.setFlat(True)
        self.editButton.setObjectName("settingDlgBtn")
        self.loadDomain = QPushButton(u"加载域名")
        self.loadDomain.setFixedSize(75,27)
        self.loadDomain.setFlat(True)
        self.loadDomain.setObjectName("settingDlgBtn")
        
        self.centerLabel = QLabel(u"平台")
        self.ipLabel = QLabel(u"IP地址")
        self.domainLabel = QLabel(u"域名")
        
        self.comboCenter = QComboBox()
        self.comboCenter.setFixedWidth(200)
        

        self.lineEditIp = QLineEdit(self)
        self.lineEditIp.setFixedWidth(300)
        
        self.lineEditDomain = QLineEdit()
        self.lineEditDomain.setFixedWidth(300)

        updateBox = QGroupBox()
        updateBox.setTitle(u"自动更新")
        updateLayout = QHBoxLayout()
        updateLayout.addSpacing(20)
        updateLayout.addWidget(self.centerLabel)
        updateLayout.addSpacing(20)
        updateLayout.addWidget(self.comboCenter)
        updateLayout.addSpacing(50)
        updateLayout.addWidget(self.loadDomain)
        updateLayout.addSpacing(50)
        updateBox.setLayout(updateLayout)
        
        self.closeButton = QPushButton(u"关闭")
        self.closeButton.setObjectName("settingDlgBtn")
        self.closeButton.setFixedSize(75,27)
        self.closeButton.setFlat(True)
        closeButtonLayout = QHBoxLayout()
        closeButtonLayout.addStretch()
        closeButtonLayout.addWidget(self.closeButton)
        
        hButtonLayout = QHBoxLayout()
        hButtonLayout.addStretch()

        hButtonLayout.addWidget(self.editButton)
        hButtonLayout.addWidget(self.deleteButton)
        
        addBox = QGroupBox()
        addBox.setTitle(u"添加域名")
        addLayout = QGridLayout()
        addLayout.setSpacing(10)

        addLayout.addWidget(self.ipLabel,0,0)
        addLayout.addWidget(self.lineEditIp,0,1)
        addLayout.addWidget(self.domainLabel,1,0)
        addLayout.addWidget(self.lineEditDomain,1,1)
        addLayout.addWidget(self.addButton,2,2)
        myAddLayout = QHBoxLayout()
        myAddLayout.addSpacing(20)
        myAddLayout.addLayout(addLayout)
        myAddLayout.addSpacing(20)
        addBox.setLayout(myAddLayout)
        
        
        miniLayout = QVBoxLayout()
        miniLayout.addSpacing(10)
        miniLayout.addWidget(updateBox)
        miniLayout.addWidget(self.tabView)
        miniLayout.addLayout(hButtonLayout)
        miniLayout.addWidget(addBox)
        miniLayout.addLayout(closeButtonLayout)
        
        
        self.mainLayout = QHBoxLayout(self)
        self.mainLayout.addSpacing(50)
        self.mainLayout.addLayout(miniLayout)
        self.mainLayout.addSpacing(50)
        
        self.connect(self.closeButton, SIGNAL("clicked()"),self.closeTabWidget)
        self.connect(self.addButton, SIGNAL("clicked()"),self.on_pushButtonAddHost_clicked)
        self.connect(self.loadDomain, SIGNAL("clicked()"),self.on_pushButtonDomain_clicked)
        self.connect(self.deleteButton, SIGNAL("clicked()"),self.on_pushButtonDeleHost_clicked)
        self.connect(self.editButton, SIGNAL("clicked()"),self.on_pushButtonEdit_clicked)
        self.connect(self.editDlg, SIGNAL("edithostover"),self.editHost)
        
        self.refreshTable()
            
        LogRecord.instance().logger.info(u"得到平台列表，并且更新在combo中")
        
        self.freshHostCenterList()
        
    def refreshTable(self):
        LogRecord.instance().logger.info(u"得到文件中的主机列表，并且更新在表格中")
        res = self.hostop.getHostList()
        if res == -1 or res == -2:
            self.num = 0
        else:
            self.num = len(res)
        self.tabView.setRowCount(self.num)
        for i in range(self.num):
            self.setRowData(i,res[i]["hostip"],res[i]["hostdes"])
            
    def slotRead(self,item):
        print (item.text())
    def autoUpdateDomain(self):
        LogRecord.instance().logger.info(u"从所选则的平台获取相应的域名")
        if (self.comboCenter.count() <= 0):
            LogRecord.instance().logger.info("平台列表为空！")
            return
        index = self.comboCenter.count() - 1
        netIp = self.comboCenter.itemData(index, Qt.UserRole + 1).toString()
        netPort = self.comboCenter.itemData(index, Qt.UserRole + 2).toString()
        netSsl = self.comboCenter.itemData(index, Qt.UserRole + 3).toString()
        
        serverUrl = netIp + ":" + netPort
        LogRecord.instance().logger.info(u"更新域名文件")
        if (not self.hostop.updateHost(serverUrl, netSsl)):
            LogRecord.instance().logger.info(u"自动更新域失败!")
            return
        #刷新表格内容
        LogRecord.instance().logger.info(u"得到文件中的域名列表")
        hostList = self.hostop.getHostList()
        num = len(hostList)
        self.tabView.setRowCount(num)
        for i in range(num):
            self.setRowData(i,hostList[i]["hostip"],hostList[i]["hostdes"])
    
        if (num > 0):
            self.tabView.selectRow(num-1)
    
        LogRecord.instance().logger.info(u"更新域成功!")
        
    def on_pushButtonDomain_clicked(self):
        LogRecord.instance().logger.info(u"从所选则的平台获取相应的域名")
        if (self.comboCenter.count() <= 0):
            InfoHintDialog(u"请添加相应的平台!").exec_()
            return
        index = self.comboCenter.currentIndex()
        netIp = self.comboCenter.itemData(index, Qt.UserRole + 1).toString()
        netPort = self.comboCenter.itemData(index, Qt.UserRole + 2).toString()
        netSsl = self.comboCenter.itemData(index, Qt.UserRole + 3).toString()
        
        serverUrl = netIp + ":" + netPort
        LogRecord.instance().logger.info(u"更新域名文件")
        
        """update for pbc on 2015.09.15"""
        temp_hostop_retu = self.hostop.updateHost(serverUrl, netSsl)
        if(temp_hostop_retu == "False"):
            InfoHintDialog(u'未检测到可添加的域名！').exec_()
            return
        elif(temp_hostop_retu == False):
            return
        

        #刷新表格内容
        LogRecord.instance().logger.info(u"得到文件中的域名列表")
        hostList = self.hostop.getHostList()
        num = len(hostList)
        self.tabView.setRowCount(num)
        
        for i in range(num):
            self.setRowData(i,hostList[i]["hostip"],hostList[i]["hostdes"])
    
        if (num > 0):
            self.tabView.selectRow(num-1)
    
        InfoHintDialog(u"更新域成功!").exec_()
       

    def on_tableWidgetHost_customContextMenuRequested(self,pos):
        LogRecord.instance().logger.info(u"右键菜单")
        item = self.tabView.itemAt(pos)
        if (item != None):
            self.hostTableMenu.clear()
            self.hostTableMenu.addAction(self.delHostAction)
            self.hostTableMenu.addAction(self.editHostAction)
            self.hostTableMenu.exec_(QCursor.pos())
    def freshHostCenterList(self):
        #获取网络列表
        netSwitchList = self.centerApi.getNetSwitchList()
        self.comboCenter.clear()
        for i in range(len(netSwitchList)):
            netName = netSwitchList[i]["netName"]
            netIp = netSwitchList[i]["netIp"]
            netPort = netSwitchList[i]["netPort"]
            ssl = netSwitchList[i]["netSsl"]
            self.comboCenter.addItem(netName)
            self.comboCenter.setItemData(i, netName, Qt.UserRole)
            self.comboCenter.setItemData(i, netIp, Qt.UserRole + 1)
            self.comboCenter.setItemData(i, netPort, Qt.UserRole + 2)
            self.comboCenter.setItemData(i, ssl, Qt.UserRole + 3)
    
    def on_pushButtonEdit_clicked(self):
        LogRecord.instance().logger.info(u"点击编辑按钮")
        itemList = self.tabView.selectedItems()
        if len(itemList) == 0 :
            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)
        desktop = QApplication.desktop()
        moveWidth = (desktop.width()-self.editDlg.width())/2
        moveHeight = (desktop.height() - self.editDlg.height())/2
        self.editDlg.move(QPoint(moveWidth,moveHeight))
        
    def editAction(self):
        currentRow = self.tabView.currentRow()
        netIpItem = self.tabView.item(currentRow, 0)
        currentIp = netIpItem.text()
        netNameItem = self.tabView.item(currentRow, 1)
        currentName = netNameItem.text()
        info = {}
        info["hostip"] = currentIp
        info["hostdes"] = currentName
        delist = []
        delist.append(info)
        self.hostop.deleHostCont(delist)
        
        self.editDlg.show()
        self.editDlg.setHostInfo(info)
        self.editDlg.move(setting.globalfunc.moveToCenter(self.editDlg.width(), self.editDlg.height()))
        
    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])$'
        itemList = self.tabView.selectedItems()
        if len(itemList) == 0 :
            #QMessageBox.information(self,u"信息",u"请先选择某一个要编辑的域")
            InfoHintDialog(u"请先选择某一个要编辑的域").exec_()
            return
        hostip = itemList[0].text()
        hostname = itemList[1].text()
        info = {}
        info["hostip"] = hostip
        info["hostdes"] = hostname
        delist = []
        delist.append(info)        
        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
        self.hostop.deleHostCont(delist)
        itemList = {}
        itemList["hostdes"] = name
        itemList["hostip"] = ip
        
        if not self.hostop.checkItemValid_2(itemList):
            InfoHintDialog(u"当前域名或IP已经存在").exec_()
            return
        
        currentRow = self.tabView.currentRow()
        netIpItem = self.tabView.item(currentRow, 0)
        currentIp = netIpItem.text()
        netNameItem = self.tabView.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)
        
        lastList = self.hostop.getHostList()
        num = len(lastList)
        self.tabView.setRowCount(num)
        for i in range(num):
            self.setRowData(i, lastList[i]["hostip"], lastList[i]["hostdes"])
        self.editDlg.close()
        
        InfoHintDialog(u"域名修改成功").exec_()
        
    def setRowData(self,row,hostip,hostdes):
        pTWItemId = QTableWidgetItem(hostip)
        pTWItemId.setTextAlignment(Qt.AlignCenter)
        self.tabView.setItem(row, 0, pTWItemId)
        pTWItemName = QTableWidgetItem(hostdes)
        pTWItemName.setTextAlignment(Qt.AlignCenter)
        self.tabView.setItem(row, 1, pTWItemName)
    def on_pushButtonDeleHost_clicked(self):
        #删除选中行
        LogRecord.instance().logger.info(u"删除域名按钮")
        itemList = self.tabView.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().logger.info(u"删除选中行")
        if 0 != self.hostop.deleHostCont(deleHostList):
            InfoHintDialog(u"删除相应的域名失败").exec_()
        
        LogRecord.instance().logger.info(u"得到文件中的主机列表，并且更新在表格中")
        hostList = self.hostop.getHostList()
        num = len(hostList)
        self.tabView.setRowCount(num)
        for i in range(num):
            self.setRowData(i, hostList[i]["hostip"], hostList[i]["hostdes"])

    
    def on_pushButtonAddHost_clicked(self):
        LogRecord.instance().logger.info(u"添加域名按钮点击")
        ip = self.lineEditIp.text().trimmed()
        hostName = self.lineEditDomain.text().trimmed()
        
        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_()
            self.lineEditIp.setFocus()
            return

        itemList = {}
        itemList["hostdes"] = hostName
        itemList["hostip"] = ip
        
        if not self.hostop.checkItemValid_2(itemList):
            InfoHintDialog(u'当前域名或IP已经存在').exec_()
            return

        self.hostop.writeHostFile(itemList)
        
        self.lineEditIp.clear()
        self.lineEditDomain.setText("")
        self.lineEditIp.setFocus()
        
        hostList = self.hostop.getHostList()
        num = len(hostList)
        self.tabView.setRowCount(num)
        
        for i in range(num):
            self.setRowData(i, hostList[i]["hostip"], hostList[i]["hostdes"])
            
        if (num > 0):
            self.tabView.selectRow(num-1)
        
    
    def on_tableWidgetHost_itemDoubleClicked(self,item):
        self.addButton.hide()
        self.saveButton.show()
  
    def closeTabWidget(self):
        self.emit(SIGNAL("closetabwidget"))        
        


        
      