#coding:utf-8

import time

from PyQt4.Qt import SLOT
from PyQt4.QtCore import QEventLoop, QTimer, QString, SIGNAL, QUrl, QThread, QByteArray
from PyQt4.QtNetwork import QNetworkAccessManager, QSsl, QSslSocket, QSslConfiguration, QNetworkRequest
from PyQt4.QtXml import QDomDocument

from base import globalfunc
from base.storeinfoparser import StoreInfoParser
from common import commondata
from register.imacinfo import ImacInfo
from setting.centerapi import CenterApi
from setting.getnetinfo import NetCtl



class NetSwitchTd(QThread):
    def __init__(self,parent=None):
        super(NetSwitchTd,self).__init__(parent)
     
        self.func = "AUTO_GET_NETWORK"
        self.netCtl = NetCtl()
        self.centerApi = CenterApi()
        self.imacInfo = ImacInfo()

    def setFunType(self,type):
        self.func = type
    
    def setNetInfo(self,info):
        self.netInfo = info
    
    def setNetID(self,id):
        self.netId = id
    
    def autoGetNetworkFunc(self):   #得到每个平台，以及每个平台对应的证书
        self.emit(SIGNAL("networkSwitchSignal"),1)
        ok = self.centerApi.restartNetwork() #重启网络
        if (not ok):
            self.emit(SIGNAL("networkSwitchSignal"),-1)
            return
 
        
        self.emit(SIGNAL("networkSwitchSignal"),2)
        print ("start net switch")
        #查询可连接的网络
        self.netSwitchList = self.centerApi.getNetSwitchList()#的到network——switch列表，centernetworklist
        num = len(self.netSwitchList)
        
       
        for i in range(num):
            serverip = self.netSwitchList[i]["netIp"]
            serverport = self.netSwitchList[i]["netPort"]
            ssl = self.netSwitchList[i]["netSsl"]
            caName = self.netSwitchList[i]["netCaName"]
            wget = ""
            if(ssl == "true"):
                wget = "wget -t 1 -T 3 --no-check-certificate -O " + commondata.CA_NAME + "/ca_temp.pem https://"
            else:
                wget = "wget -t 1 -T 3 -O " + commondata.CA_NAME + "/ca_temp.pem http://"
    
            res = self.centerApi.saveCurSet(serverip,serverport,wget,ssl, caName)
            if( 0 == res ):
            
                self.emit(SIGNAL("networkSwitchSignal"),0)
                return
        
        self.emit(SIGNAL("networkSwitchSignal"),-2)
        return
    
    
    def getDomains(self,timeout):
    
        ssl = self.netInfo["netSsl"]
        centerIp = self.netInfo["netIp"]
        centerPort= self.netInfo["netPort"]
        serverUrl = centerIp + ":" + centerPort
    
        netMgmt = QNetworkAccessManager()
        eventLoop = QEventLoop()
        http = QString()
        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/domains"
    
        request = QNetworkRequest()
        config = QSslConfiguration()
        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(timeout)
        eventLoop.exec_()
    
  
        vmInfo = reply.readAll()
        reply.deleteLater()
    
        content = QString(vmInfo)
        if (content == "0"):
            return -1
        elif (content.contains("This request requires HTTP authentication")):
            return -2
        return 0
    
    def registerTerminalInfo(self):
        ssl = self.netInfo["netSsl"]
        centerIp = self.netInfo["netIp"]
        centerPort= self.netInfo["netPort"]
        serverUrl = centerIp + ":" + centerPort
        
        vmMgmt = QNetworkAccessManager()
        vmActLoop = QEventLoop()
        timeout = 60 * 1000
        t = QTimer()
        t.setSingleShot(True)
    
        self.connect(vmMgmt, SIGNAL("finished(QNetworkReply*)"),vmActLoop,SLOT("quit()"))
        self.connect(t, SIGNAL("timeout()"),vmActLoop,SLOT("quit()"))
        
        
        cpuInfo = self.imacInfo.getCpuInfo()
        memSize = self.imacInfo.getMemInfo()
        ip = self.imacInfo.get_ip_address()
        macInfo = self.imacInfo.get_mac_address()
        currentDate = globalfunc.getCurrentSystemDate()
            
        if(ssl == "true"):
            http = "https"
        else:
            http = "http"
                
        strUrl = http + "://" + serverUrl + "/massclouds-center/api/terminals"
        postData = QByteArray()
        
        data = QString("<terminal>"
                       "<cpu_type>cpu %1</cpu_type>"
                       "<mem_size>%2</mem_size>"
                       "<ip>%3</ip>"
                       "<mac_address>%4</mac_address>"
                       "<terminaltype>1</terminaltype>"
                       "<terminaldate>%10</terminaldate>"
                       "</terminal>").arg(cpuInfo).arg(memSize).arg(ip).arg(macInfo).arg(currentDate)

        postData.append(data.toAscii())
        request = QNetworkRequest()
        config = QSslConfiguration()
        config.setPeerVerifyMode(QSslSocket.VerifyNone)
        config.setProtocol(QSsl.TlsV1)
        request.setSslConfiguration(config)
    
        request.setUrl(QUrl(strUrl))
        
        request.setHeader(QNetworkRequest.ContentTypeHeader,"application/xml")
        contentLength = postData.size()
        request.setRawHeader("isClient","true")
        request.setHeader(QNetworkRequest.ContentLengthHeader,contentLength)
    
    
        reply_ac = vmMgmt.post(request,postData)
        t.start(timeout)
        
        vmActLoop.exec_()
    
        ac_result = reply_ac.readAll()
        reply_ac.deleteLater()
        
        
        dom_sre = QDomDocument()
        dom_sre.setContent(ac_result)
        
        actions_re = dom_sre.elementsByTagName("registerCode")
        
        registerid = ""
        
        for i in range(len(actions_re)):
            node_action = actions_re.at(i)
            registerid = node_action.toElement().text()

            resu_list = node_action.childNodes()
            for j in range(len(resu_list)):
                resu_list_ = resu_list.at(j)
                if(resu_list_.toElement().tagName()=="mac_address"):
                    status_c = len(resu_list_.toElement().childNodes())
                    mac = resu_list_.toElement().text()
                #判断该动作是否成功
                if(resu_list_.toElement().tagName()=="status"):
                    status_c = len(resu_list_.toElement().childNodes())
                    for m in range(status_c):
                        status_cn_s = resu_list_.toElement().childNodes().at(m)
                        if(status_cn_s.toElement().tagName()=="state"):
                            status = status_cn_s.toElement().text()
                            
                if(resu_list_.toElement().tagName()=="name"):
                    status_c = len(resu_list_.toElement().childNodes())
                    name = resu_list_.toElement().text()
        return registerid
    
    def getTerminalId(self):
        ssl = self.netInfo["netSsl"]
        centerIp = self.netInfo["netIp"]
        centerPort= self.netInfo["netPort"]
        serverUrl = centerIp + ":" + centerPort
        currentCenter = serverUrl
        terminalIdListl = StoreInfoParser.instance().getTerminalId()
        terminalIdList = self.toList(terminalIdListl)
        if currentCenter == "":
            return ""
        else:
            for i in range(len(terminalIdList)):
                if terminalIdList[i].split(":")[0] == currentCenter.split(":")[0]:
                    return terminalIdList[i].split(":")[1]
        
        return ""
    
    def setTerminalId(self,registerid):
        ssl = self.netInfo["netSsl"]
        centerIp = self.netInfo["netIp"]
        centerPort= self.netInfo["netPort"]
        serverUrl = centerIp + ":" + centerPort
        currentCenter = serverUrl
        if currentCenter == "":
            return
        bakid = ""
        storeinfo = currentCenter.split(":")[0] + ":" + registerid
        terminalIdListl = StoreInfoParser.instance().getTerminalId()
        terminalIdList = self.toList(terminalIdListl)
        for i in range(len(terminalIdList)):
            if terminalIdList[i].split(":")[0] == currentCenter.split(":")[0]:
                bakid = terminalIdList[i]
        if bakid != "":       
            terminalIdList.remove(bakid)
            
        terminalIdList.append(storeinfo)
        StoreInfoParser.instance().setTerminalId(terminalIdList)
    def toList(self,listStr):
        listT = []
        listS = "a"
        if(type(listStr) == type(listS)):
            if (listStr == "" or listStr == "None" or listStr == "[]"):
                return []
            else:
                listList = []
                list = listStr.split(",")
                for i in range(len(list)):
                    listList.append(list[i].split("'")[1])
                return listList
        elif(type(listStr) == type(listT)):
            return listStr  
        return []      
    
    def addNetworkItem(self):#将平台添加进入配置文件中
      
        
        self.emit(SIGNAL("addNetworkItemSignal"),3)
        #获得相应的域
        res = 1
        for i in range(6):
            res = self.getDomains(3000) #获得平台主机地址
            if (res == 0):
                break
            time.sleep(1)
    
        if (res == -1):
            self.emit(SIGNAL("addNetworkItemSignal"),-10)
            return
        elif (res == -2):
            self.emit(SIGNAL("addNetworkItemSignal"),-11)
            return
    
        
        ssl = self.netInfo["netSsl"]
        centerIp = self.netInfo["netIp"]
        centerPort= self.netInfo["netPort"]
        centerName = self.netInfo["netName"]
        centerID = self.netInfo["netId"]
        networkName = self.netInfo["networkName"]
        netSwitch = self.netInfo["netSwitch"]
        
        #获得证书
        wget = ""
        if(ssl == "true"):
            wget = "wget -t 1 --no-check-certificate -O " + commondata.CA_NAME + "/ca_temp.pem https://"
        else:
            wget = "wget -t 1 -O " + commondata.CA_NAME + "/ca_temp.pem http://"
    
        self.emit(SIGNAL("addNetworkItemSignal"),2)
        if(not self.centerApi.getCaFile(centerIp+":"+centerPort , wget)):#获得证书
            self.emit(SIGNAL("addNetworkItemSignal"),-9)
            return
    
        result = self.centerApi.setNetworkSwitch(centerName, centerIp, centerPort, ssl, centerID, networkName,netSwitch)#填入平台配置文件
        if (-1 == result):
            self.emit(SIGNAL("addNetworkItemSignal"),-1)
        elif(-2 == result):
            self.emit(SIGNAL("addNetworkItemSignal"),-2)
        elif(-3 == result):
            self.emit(SIGNAL("addNetworkItemSignal"),-3)
        elif(-4 == result):
            self.emit(SIGNAL("addNetworkItemSignal"),-4)
        elif(-5 == result):
            self.emit(SIGNAL("addNetworkItemSignal"),-5)
        elif(-6 == result):
            self.emit(SIGNAL("addNetworkItemSignal"),-6)
        elif(-7 == result):
            self.emit(SIGNAL("addNetworkItemSignal"),-7)
        elif(0 == result):
            self.emit(SIGNAL("addNetworkItemSignal"),0)
        
    
    
    def authCertificate(self):
        self.emit(SIGNAL("authCertificateSignal"),1)
        ok = self.centerApi.restartNetwork()#重启网络
        if (not ok):
            self.emit(SIGNAL("authCertificateSignal"),-5)
            return
        
        ssl = self.netInfo["netSsl"]
        serverip = self.netInfo["netIp"]
        serverport= self.netInfo["netPort"]
        caName = self.netInfo["netCaName"]
    
        wget = ""
        if(ssl == "true"):
            wget = "wget -t 1 -T 3 --no-check-certificate -O " + commondata.CA_NAME + "/ca_temp.pem https://"
        else:
            wget = "wget -t 1 -T 3 -O " + commondata.CA_NAME + "/ca_temp.pem http://"
    
        self.emit(SIGNAL("authCertificateSignal"),2)
        res = self.centerApi.saveCurSet(serverip,serverport,wget,ssl,caName)#平台保存
        if( 0 == res ):
            self.emit(SIGNAL("authCertificateSignal"),0)
        elif( -1 == res ):
            self.emit(SIGNAL("authCertificateSignal"),-1)
        elif( -2 == res ):
            self.emit(SIGNAL("authCertificateSignal"),-2)
        elif( -3 == res ):
            self.emit(SIGNAL("authCertificateSignal"),-3)
        else:
            self.emit(SIGNAL("authCertificateSignal"),-4)
        return
    
    def configNetInterfaceFile(self,netId):#本地ip地址获取和设置
        netType = QString()
       
        netAddressList = self.netCtl.getNetAddressList()
        count = len(netAddressList)
        for i in range(count):
            if (netId == netAddressList[i]["addressID"]):
                if (QString(netAddressList[i]["netName"]).startsWith("dhcp-")):
                    netType = "dhcp"
                else:
                    netType = "static"
                netAddress = netAddressList[i]
                break
        
        #将地址设置到eth0中，并且保存到current——net文件中   
        if (netType == "dhcp"):
            eth = netAddress["netName"].split("-")[1]
            if (not self.netCtl.setAuto(eth)):
                return False
            #把当前的网络配置信息写入文件
            self.netCtl.setCurrentNetworkInfo(netAddress["netName"],"",netId)
        elif(netType == "static"):
            netName = netAddress["netName"]
            ip = netAddress["netIp"]
            mask = netAddress["netMast"]
            gateway = netAddress["netGate"]
            dns1 = netAddress["netDNS1"]
            dns2 = netAddress["netDNS2"]
            eth = netAddress["netCard"]
            ID = netAddress["addressID"]
            if (not self.netCtl.setStatic(eth, ip, mask, gateway, dns1, dns2)):
                return False
            #把当前的网络配置信息写入文件
            self.netCtl.setCurrentNetworkInfo(netName, ip, ID)
            
        return True
    def restartNetwork(self):
        if (not self.configNetInterfaceFile(self.netId)):
            self.emit(SIGNAL("restartNetworkSignal"),-1)
            return
        self.emit(SIGNAL("restartNetworkSignal"),1)
        self.emit(SIGNAL("restartNetworkSignal"),0)
    def run(self):
        if self.func == "AUTO_GET_NETWORK":
            self.autoGetNetworkFunc()
        elif self.func == "ADD_NETWORK_ITEM":
            self.addNetworkItem()
        elif self.func == "AUTH_CERTIFICATE":
            self.authCertificate()
        elif self.func == "RESTART_NET_SERVERS":
            self.restartNetwork()
        
    

