#coding:utf-8
'''
Created on Sep 26, 2014

@author: root
'''

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

from common import commondata
from desktop.userapi import UserApi


class NetworkAccessManager(QObject):
    timer = QTimer()
    timer.setSingleShot(True)
    def __init__(self,parent=None):
        super(NetworkAccessManager,self).__init__(parent)
        
    
    @classmethod
    def getRequestContext(cls, path, functionType="get", auth=True, postData=None):
        netMgmt = QNetworkAccessManager()
        eventLoop = QEventLoop()
        reply = None
        
        QObject.connect(cls.timer, SIGNAL("timeout()"), eventLoop,SLOT("quit()"))
        QObject.connect(netMgmt, SIGNAL("finished(QNetworkReply*)"), eventLoop,SLOT("quit()"))
        
        request = cls.getNetworkRequest(path, auth)
        if functionType == "get":
            reply = netMgmt.get(request)
        elif functionType == "post" or functionType == "put":
            data = QByteArray()
            data.append(QString(postData).toAscii())
            request.setHeader(QNetworkRequest.ContentTypeHeader,"application/xml")
            request.setHeader(QNetworkRequest.ContentLengthHeader,len(data))
            if functionType == "post":
                reply = netMgmt.post(request, postData)
            else:
                reply = netMgmt.put(request, postData)
            
        cls.timer.start(6*1000)
        eventLoop.exec_()
        
        requestInfo = reply.readAll()

        reply.deleteLater()
     
        return requestInfo
    
    
    @classmethod
    def getNetworkRequest(cls, path, auth):
        validPath = path
        if path == commondata.TERMINAL_LOGIN_CENTER_URL:
            validPath = commondata.VMS_CENTER_URL
        
        request = QNetworkRequest() 
        config = QSslConfiguration() 
        config.setPeerVerifyMode(QSslSocket.VerifyNone)
        config.setProtocol(QSsl.TlsV1)
        request.setSslConfiguration(config)
        request.setUrl(QUrl(cls.getServerUrl(validPath)))
        
        if auth:
            userName, userDomain, userPasswd = cls.getAuthorizationInfo()
            request.setRawHeader("Authorization", "Basic " + QByteArray(QString("%1:%2").arg(userName+"@"+userDomain).arg(userPasswd).toAscii()).toBase64())
            request.setRawHeader("Filter","true")
            request.setRawHeader("isClient","true")
            if path == commondata.TERMINAL_LOGIN_CENTER_URL:
                request.setRawHeader("isLogin","true")
        
        return request
    
    @classmethod
    def getAuthorizationInfo(cls):

        userName = UserApi.instance().getUserName()
        userDomain = UserApi.instance().getDomain()
        userPasswd = UserApi.instance().getUserPasswd()
        return userName, userDomain, userPasswd
    
    @classmethod
    def getServerUrl(cls, path):
        serverUrl = UserApi.instance().getUserServer()
        ssl = UserApi.instance().getSsl()
        http = "https" if ssl else "http"
        strUrl = http + "://" + serverUrl + path
        return strUrl
    
    
    
    


