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

from base.storeinfoparser import StoreInfoParser
from PyQt4.QtCore import QObject, QEventLoop, QTimer, SIGNAL, SLOT, QString,\
    QUrl, QByteArray, QCryptographicHash, QTextCodec
from PyQt4.QtXml import QDomDocument, QDomElement, QDomNode, QDomNodeList


class AutoLog(QObject):
    def __init__(self,parent=None):
        super(AutoLog,self).__init__(parent)
    #读取自动登录文件，看是否已经设置自动登录
    def showCurSet(self):
        #读取自动登录文件
       
        autoinfo = StoreInfoParser.instance().getLoginSet()
        list = autoinfo.split(",")
        username = list[0]
        return username
    
    def cancelAuto(self):

        input= ""
        StoreInfoParser.instance().setLoginSet(input)
        return True
    
    def getDomains(self):
        result = []
        netMgmt = QNetworkAccessManager()
        eventLoop = QEventLoop()
        timeout = 3 * 1000
        t = QTimer()
        t.setSingleShot(True)
    
        self.connect(netMgmt,SIGNAL("finished(QNetworkReply*)"),eventLoop,SLOT("quit()"))
        self.connect(t,SIGNAL("timeout()"),eventLoop,SLOT("quit()"))
        http = QString()
     
        serverUrl = QString(self.getUserServer())
        
        if(serverUrl == ""):   #默认不显示域名
            return result
        if(self.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()
        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)):
                
                    node = QDomNode()
                    node = list.at(i)
                    elm = QDomElement()
                    if(node.isElement()):
                        elm = QDomElement()
                        elm = node.toElement()
                        if(not QString.compare("name", elm.tagName())):
                       
                            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
        
    def sendRequest(self,usernames,passwd,domain):
    
        
        url = QString(self.getUserServer())
        if( url.isEmpty() or url.isNull() ):
            return -1
    
        password = QString()
        if(domain.toLower() == "internal"):
            ba = QByteArray()
            bb = QByteArray()
            md = QCryptographicHash(QCryptographicHash.Md5)
            ba.append(passwd)
            md.addData(ba)
            bb = md.result()
            password.append(bb.toHex())
            
        else:
            password = passwd
        
        netMgmt = QNetworkAccessManager()
        eventLoop = QEventLoop() 
        timeout = 60 * 1000
        t = QTimer()
        t.setSingleShot(True)
    
        self.connect(netMgmt, SIGNAL("finished(QNetworkReply*)"),eventLoop,SLOT("quit()"))
        self.connect(t,SIGNAL("timeout()"),eventLoop,SLOT("quit()"))
        http = QString() 
        if(self.ssl == "true"):
            http = "https"
        else:
            http = "http"
            
        strUrl = http+"://"+url+"/massclouds-center/api/vms"
    
        request = QNetworkRequest()
        config = QSslConfiguration()
    
        config.setPeerVerifyMode(QSslSocket.VerifyNone)
        config.setProtocol(QSsl.TlsV1)
        request.setSslConfiguration(config)
        request.setUrl(QUrl(strUrl))
        request.setRawHeader("Authorization", "Basic " + QByteArray(QString("%1:%2").arg(usernames+"@"+domain).arg(password).toAscii()).toBase64());
        request.setRawHeader("Filter","true");
        request.setRawHeader("isClient","true")
    
        reply = netMgmt.get(request)
        t.start(timeout)
        eventLoop.exec_()
    
       
        codec = QTextCodec.codecForName("UTF-8")
        vmInfo = QString(codec.toUnicode(reply.readAll()))
        reply.deleteLater()
    
        if(vmInfo.length() == 0):
            return -2
        else:
            stri = QString("HTTP Status 401")
            if(vmInfo.contains(stri) =="true"):
                return -3
  
        input = usernames + "," + password + "," + domain
        StoreInfoParser.instance().setLoginSet(input)
        return 0
    