#coding:utf-8
'''
Created on Sep 4, 2014
@author: root
'''
from PyQt4.QtCore import *
from PyQt4.QtNetwork import QSsl,QNetworkAccessManager,QNetworkRequest,QSslConfiguration,QSslSocket
from PyQt4.QtXml import *

# from base.storeinfoparser import StoreInfoParser
from model.cfg.storeinfoparser import StoreInfoParser


class AutoLog(QObject):
    def __init__(self,parent=None):
        super(AutoLog,self).__init__(parent)

    
    def getDomains(self):
        result = []
        netMgmt = QNetworkAccessManager()
        eventLoop = QEventLoop()
        timeout = 3 * 1000
        t = QTimer()
        t.setSingleShot(True)
    
        self.connect(netMgmt,SIGNAL("finished(QNetworkReply*)"),eventLoop.quit)
        self.connect(t,SIGNAL("timeout()"),eventLoop.quit)
        http = QString()
        #ssl = QString() 
        serverUrl = QString(self.getUserServer())
        
        if(serverUrl == ""):   #默认不显示域名
            return result
        if(self.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_()
        
        vmInfo = reply.readAll()
        reply.deleteLater()
        dom = QDomDocument()
        dom.setContent(vmInfo)
        domElem = QDomElement(dom.documentElement())#返回跟节点
        n = QDomNode(domElem.firstChild())#返回跟节点的第一个子节点
        #如果节点不为空，则转到下一节点
        while(not n.isNull()):
            if(n.isElement()):
                e = QDomElement()#如果节点为元素，则转为元素
                e = n.toElement()
                #获得此元素下的所有节点列表
                list = QDomNodeList()
                list = e.childNodes()
                for i in range(len(list)):
                #for(int i=0; i<list.count(); i++)
                    node = QDomNode()
                    node = list.at(i)
                    elm = QDomElement()
                    if(node.isElement()):
                        elm = QDomElement()
                        elm = node.toElement()
                        if(not QString.compare("name", elm.tagName())):
                            #result << elm.text()
                            result.append(elm.text())
                    node = elm.nextSibling()
            n = n.nextSibling()
        return result
    def getUserServer(self):
        url = StoreInfoParser.instance().getCurrenCenter()
        list = url.split(":")
        if(len(list)>1):
                url = list[0]+":"+list[1]
        if(len(list)>2):
                self.ssl=list[2]
        else:
                self.ssl="false"
        return url
        