#coding:utf-8

from PyQt4.QtCore import QObject,SIGNAL,QUrl,QString,QEventLoop,QTimer,QFile,QIODevice,QTextStream,QStringList
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest, QSslSocket, QSslConfiguration,QSsl
from PyQt4.QtXml import QDomDocument,QDomNode
import os
from common import commondata


class Hostop(QObject):
    def __init__(self,parent=None):
        super(Hostop,self).__init__(parent)
        
    
    def getHostFile(self):
        if (not QFile.exists(commondata.HOSTS_FILE)):
            return -1
        file_con = QFile(commondata.HOSTS_FILE)
        if(not file_con.open(QIODevice.ReadOnly)):
            file_con.close()
            return -1
        if(file_con.size()==0):
            file_con.close()
            return -2
        fs = QTextStream(file_con)
        hostcon = fs.readAll()
        return hostcon

    def getHostList(self):
        res = self.getHostFile()
        if( -1 == res):
            return [] #读ｈｏｓｔ文件失败
        elif(-2 ==res ):
            return [] #ｈｏｓｔ文件为空
        elif(res == ""):
            return []
    
        #对hostcon进行处理
        temp = res.split("\n")
        hostList = []
        #去除注释行
        for i in range(len(temp)):
            if( temp[i].startsWith("#") ):
                continue
            temp[i]= temp[i].simplified()
            
            str = temp[i].split(" ")
            num = len(str)
            if( num > 1):
                host = {}
                host["hostip"] = str[0]
                host["hostdes"] = str[1]
                hostList.append(host)
        return hostList

    def deleHostCont(self,deleHostList):
        os.system("umount /etc/hosts")
        os.system("cp -f /config/etc/hosts /etc/hosts")
        res = self.getHostFile()
        if( -1 == res):
            return -1 #读ｈｏｓｔ文件失败
        elif(-2 ==res ):
            return -2 #ｈｏｓｔ文件为空
        
        temp = res.split("\n")
        row = QStringList() 
        
        for j in range(len(temp)):
            temp[j]= QString(temp[j]).simplified()
            tempcon = temp[j].split(" ")
            if(len(tempcon)>1):
                for i in range(len(deleHostList)):
                    if(tempcon[0] == deleHostList[i]["hostip"] and tempcon[1]== deleHostList[i]["hostdes"] and not QString(temp[j]).startsWith("#")):
                        row.append(QString.number(j))
        
        k=0
        for m in range(len(row)):
            num = int(row[m])+1-k
            a1 = "sed -i '"+ str(num)+ "d' " + commondata.HOSTS_FILE
            res = os.system(a1)
            k+=1
        
        os.system("cp -f /etc/hosts /config/etc/hosts")
        os.system("mount --bind /config/etc/hosts /etc/hosts")
        return 0
        
    def writeHostList(self,hostList):
        os.system("umount /etc/hosts")
        os.system("cp -f /config/etc/hosts /etc/hosts")
        text = QString()
        for i in range(len(hostList)):
            text += hostList[i]["hostip"] + "    " + hostList[i]["hostdes"] +"\n"
        cmdDelTmp = "sed -i '1, $d' /etc/hosts"
        os.system(cmdDelTmp)
        file = QFile(commondata.HOSTS_FILE)
        if(not file.open(QIODevice.WriteOnly | QIODevice.Text)):
            os.system("cp -f /etc/hosts /config/etc/hosts")
            os.system("mount --bind /config/etc/hosts /etc/hosts")
            return
        inp = QTextStream(file)
        inp<<text
        file.close()
        os.system("cp -f /etc/hosts /config/etc/hosts")
        os.system("mount --bind /config/etc/hosts /etc/hosts")
    def writeHostFile(self,hostList):
        content = hostList["hostip"] + "    " +hostList["hostdes"] + "\n"
        os.system("umount /etc/hosts")
        os.system("cp -f /config/etc/hosts /etc/hosts")
        hostFile = QFile(commondata.HOSTS_FILE)
        if not hostFile.open(QIODevice.Append):
            hostFile.close()
            os.system("cp -f /etc/hosts /config/etc/hosts")
            os.system("mount --bind /config/etc/hosts /etc/hosts")
            return False
        s = QTextStream(hostFile)
        s << content
        hostFile.close()
        os.system("cp -f /etc/hosts /config/etc/hosts")
        os.system("mount --bind /config/etc/hosts /etc/hosts")
        return True
    def checkItemValid(self,itemList):
        ip = itemList["hostip"]
        host = itemList["hostdes"]
        hostList = self.getHostList()
        for i in range(len(hostList)):
            if hostList[i]["hostdes"] == host:
                return False
            
        return True
    def updateHost(self,serverUrl,ssl):
        content = self.getRequestContent(serverUrl, ssl)
        if (len(content) <= 0):
            return False
    
        hostList = self.parseRequestContent(content)
        if (len(hostList) <= 0):
            return False
        if (hostList[0] == "null"):
            return False
        oldHostList = self.getHostList()
    
        lastHostList = self.combinationHost(hostList,oldHostList)
        self.writeHostList(lastHostList)
        
        return True

    def combinationHost(self,newHostList,oldHostList):
        tempList = oldHostList
        for item in newHostList:
            host = item.split(":")[0]
            ip = item.split(":")[1]
            add = True
            for hostItem in oldHostList:
                if (hostItem["hostdes"] == host):
                    add = False
                    break
            if (add):
                tempHost = {}
                tempHost["hostip"] = ip
                tempHost["hostdes"] = host
                tempList.append(tempHost)
        return tempList
    def parseRequestContent(self,content):
        dom = QDomDocument()
        hostList = []
        hostTempList = []
        rootNode = QDomNode()
        dom.setContent(content);
        sumlist = dom.elementsByTagName("domainNameConfigs")
    
        if (len(sumlist) > 0):
            rootNode = sumlist.at(0)
        else:
            return hostList
    
        host_list = rootNode.childNodes();
        vmCount = len(host_list)
        for i in range(vmCount):
            node = host_list.at(i)
            if (node.toElement().tagName() == "domainNameConfig"):
                itemlist = node.childNodes()
                for j in range(len(itemlist)):
                    mynode = itemlist.at(j)
                    if( mynode.toElement().tagName() == "domainAndIp" ):
                        host = mynode.toElement().text()
    
        if (host != ""):
            hostTempList = host.split(";")
            for i in range(len(hostTempList)):
            
                if (not hostTempList[i].isEmpty() and not hostTempList[i].isNull() and hostTempList[i] != ""):
                    hostList.append(hostTempList[i])
                    
        return hostList
    def getUsbList(self,content):
        dom = QDomDocument()
        usbList = []
        usbTempList = []
        rootNode = QDomNode()
    
        dom.setContent(content);
    
        sumlist = dom.elementsByTagName("domainNameConfigs")
    
        if (len(sumlist) > 0):
            rootNode = sumlist.at(0)
        else:
            return usbList
    
        host_list = rootNode.childNodes();
        vmCount = len(host_list)
        usb = ""
        for i in range(vmCount):
            node = host_list.at(i)
            if (node.toElement().tagName() == "domainNameConfig"):
                itemlist = node.childNodes()
                for j in range(len(itemlist)):
                    mynode = itemlist.at(j)
                    if( mynode.toElement().tagName() == "UsbEquipment" ):
                        usb = mynode.toElement().text()
        if (usb == "null"):
            return usbList
        if (usb != ""):
            usbTempList = usb.split(";")
            for i in range(len(usbTempList)):
                if (usbTempList[i] != ""):
                    usbList.append(usbTempList[i])
                    
        return usbList
    
    def getRequestContent(self,serverUrl,ssl):
    
        request = QNetworkRequest()
        config = QSslConfiguration()
        netMgmt = QNetworkAccessManager()
        eventLoop = QEventLoop()
        t = QTimer()
        t.setSingleShot(True)
    
        self.connect(netMgmt, SIGNAL("finished(QNetworkReply*)"),eventLoop.quit)
        self.connect(t,SIGNAL("timeout()"),eventLoop.quit)
    
        if (ssl == "true"):
            http = "https"
        else:
            http = "http"
    
        strUrl = http+"://"+serverUrl + "/mcvdi-center/api/domainNameConfigs"
        config.setPeerVerifyMode(QSslSocket.VerifyNone)
        config.setProtocol(QSsl.TlsV1)
        request.setSslConfiguration(config)
        request.setUrl(QUrl(strUrl))
        reply = netMgmt.get(request)
        t.start(3000)
        eventLoop.exec_()
    
    
        requestInfo = reply.readAll()
        reply.deleteLater()
        return requestInfo
