#coding:utf-8
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 model.setting.getnetinfo import NetCtl
from model.setting.centerapi import CenterApi
from model.cfg.storeinfoparser import StoreInfoParser
from common import globalfun
from common import commondata

import model.setting.globalfunc
import time

class NetSwitchTd(QThread):
    def __init__(self,parent=None):
        super(NetSwitchTd,self).__init__(parent)
        #parentObj = 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
        #emit networkSwitchSignal(2)
        
        self.emit(SIGNAL("networkSwitchSignal"),2)
#         print "start net switch"
        #查询可连接的网络
        self.netSwitchList = self.centerApi.getNetSwitchList()#的到network——switch列表，centernetworklist
        num = len(self.netSwitchList)
        
        #for(int i=0;i<num;i++)
        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 ):
                #emit networkSwitchSignal(0);
                self.emit(SIGNAL("networkSwitchSignal"),0)
                return
        #emit networkSwitchSignal(-2)
        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.quit)
        self.connect(t,SIGNAL("timeout()"),eventLoop.quit)
    
        if(ssl == "true"):
            http = "https"
        else:
            http = "http"
        strUrl = http + "://" + serverUrl + "/mcvdi-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_()
    
        #QByteArray vmInfo = reply->readAll();
        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 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 (int i = 0; i < 6; i++)
        for i in range(6):
            res = self.getDomains(3000) #获得中心主机地址
            if (res == 0):
                break
            time.sleep(1)
    
        if (res == -1):
            #addNetworkItemSignal(-10)
            self.emit(SIGNAL("addNetworkItemSignal"),-10)
            return
        elif (res == -2):
            #addNetworkItemSignal(-11);
            self.emit(SIGNAL("addNetworkItemSignal"),-11)
            return
    
    
#         print "start add netwrok item"
    
        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://"
    
        #addNetworkItemSignal(2);
        self.emit(SIGNAL("addNetworkItemSignal"),2)
        if(not self.centerApi.getCaFile(centerIp+":"+centerPort , wget)):#获得证书
            #addNetworkItemSignal(-9)
            self.emit(SIGNAL("addNetworkItemSignal"),-9)
            return
    
        result = self.centerApi.setNetworkSwitch(centerName, centerIp, centerPort, ssl, centerID, networkName,netSwitch)#填入中心配置文件
        if (-1 == result):
            #addNetworkItemSignal(-1);
            self.emit(SIGNAL("addNetworkItemSignal"),-1)
        elif(-2 == result):
            #addNetworkItemSignal(-2);
            self.emit(SIGNAL("addNetworkItemSignal"),-2)
        elif(-3 == result):
            #addNetworkItemSignal(-3);
            self.emit(SIGNAL("addNetworkItemSignal"),-3)
        elif(-4 == result):
            #addNetworkItemSignal(-4);
            self.emit(SIGNAL("addNetworkItemSignal"),-4)
        elif(-5 == result):
            #addNetworkItemSignal(-5);
            self.emit(SIGNAL("addNetworkItemSignal"),-5)
        elif(-6 == result):
            #addNetworkItemSignal(-6);
            self.emit(SIGNAL("addNetworkItemSignal"),-6)
        elif(-7 == result):
            #addNetworkItemSignal(-7);
            self.emit(SIGNAL("addNetworkItemSignal"),-7)
        elif(0 == result):
            #addNetworkItemSignal(0);
            self.emit(SIGNAL("addNetworkItemSignal"),0)
        
    
    
    def authCertificate(self):
    
        #authCertificateSignal(1);
        self.emit(SIGNAL("authCertificateSignal"),1)
        ok = self.centerApi.restartNetwork()#重启网络
        if (not ok):
            #authCertificateSignal(-5)
            self.emit(SIGNAL("authCertificateSignal"),-5)
            return
    
#         print "start auth Certificate"
    
        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
        if (netType == "dhcp"):#如果是动态ip
            eth = netAddress["netName"].split("-")[1]
            print eth,"eth ..........................................."
            if (not self.netCtl.setAuto(eth)):
                return False
            #把当前的网络配置信息写入文件
            self.netCtl.setCurrentNetworkInfo(netAddress["netName"],"",netId)
        elif(netType == "static"):#如果是静态ip
            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()
        
        
