#coding:utf-8

import os

from PyQt4.Qt import SLOT
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

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):

        #读取/etc/hosts文件
        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)):
        #for(int i =0;i<temp.count()-1;i++)
            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  #etc/hosts"
            
            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()
        #QString fileName="/etc/hosts";
        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 checkItemValid_2(self,itemList):
        ip = itemList["hostip"]
        host = itemList["hostdes"]
        hostList = self.getHostList()
        for i in range(len(hostList)):
            if(hostList[i]["hostdes"] == host or hostList[i]["hostip"] == ip):
                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)
        
        print (lastHostList)
        
        self.writeHostList(lastHostList)
        
        return True

    def combinationHost(self,newHostList,oldHostList):    
        #  -----------------------------new methed get domain list -top - pbc created in 2015 -7- 11    
        tempList = oldHostList
        for item in newHostList:
            tmp=item.split(":")
            if(len(tmp)>1):
                host = item.split(":")[0]
                ip = item.split(":")[1]
                add = True
                for hostItem in range(len(oldHostList)):
                    old_host_name = oldHostList[hostItem]["hostdes"]
                    old_host_ip = oldHostList[hostItem]["hostip"]
                    if (old_host_name == host or old_host_ip == ip):
                        oldHostList[hostItem]["hostdes"] = host
                        oldHostList[hostItem]["hostip"] = ip
                        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("centerManagerConfigs")
    
        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() == "centerManagerConfig"):
                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("centerManagerConfigs")
    
        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() == "centerManagerConfig"):
                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 isRegister(self,content):
        dom = QDomDocument()
        registerAllow = ""
        
        rootNode = QDomNode()
    
        dom.setContent(content);
    
        sumlist = dom.elementsByTagName("centerManagerConfigs")
    
        if (len(sumlist) > 0):
            rootNode = sumlist.at(0)
        else:
            return False
    
        host_list = rootNode.childNodes();
        vmCount = len(host_list)
        for i in range(vmCount):
            node = host_list.at(i)
            if (node.toElement().tagName() == "centerManagerConfig"):
                itemlist = node.childNodes()
                for j in range(len(itemlist)):
                    mynode = itemlist.at(j)
                    if( mynode.toElement().tagName() == "terminalManageEnabled" ):
                        registerAllow = mynode.toElement().text()
        print ("registerAllow",registerAllow)
        if (registerAllow == "null" or registerAllow == "" or registerAllow == "false"):
            return False
        elif registerAllow == "true":
            return True
        else:
            return False
                    
    
    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,SLOT("quit()"))
        self.connect(t,SIGNAL("timeout()"),eventLoop,SLOT("quit()"))
    
        if (ssl == "true"):
            http = "https"
        else:
            http = "http"
    
        strUrl = http+"://"+serverUrl + "/massclouds-center/api/centerManagerConfigs"
    
        config.setPeerVerifyMode(QSslSocket.VerifyNone)
        config.setProtocol(QSsl.TlsV1)
        request.setSslConfiguration(config)
        request.setUrl(QUrl(strUrl))
        request.setRawHeader("isClient","true")
        reply = netMgmt.get(request)
        t.start(3000)
        eventLoop.exec_()
    
    
        requestInfo = reply.readAll()
        reply.deleteLater()

        return requestInfo
