# -*- coding: utf-8 -*-  

'''
Created on Oct 27, 2014

@author: raul
'''
from PyQt4.Qt import SLOT
from PyQt4.QtCore import QObject, QString, QEventLoop, QTimer, SIGNAL, QUrl, \
    QByteArray
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest, \
    QSslConfiguration, QSslSocket, QSsl

from base.storeinfoparser import StoreInfoParser


class User(QObject):
    '''
    Please use this class instead of UserApi
    '''
    _instance = None

    def __init__(self):
        '''
        Constructor
        @param name: the user name 
        @param passwd: the password of the user
        '''
        self.__initiallize()
        
    def __initiallize(self):
        '''
        All class properties should be here
        '''
        self.name = None
        self.passwd = None
        self.domain = None
        self.ssl = None
        self.personalDisks = None
        
    def getSsl(self):
        return self.ssl
    
    def getHttp(self):
        if(self.ssl):
            http = "https"
        else:
            http = "http"
        return http
    
    def updateUserInfo(self, name, passwd, domain):
        '''
        Set user name and password for this user
        @param name: the name of the user
        @param passwd: the password of the user which has been encrypted by MD5
        @param domain: the domain of the user 
        '''
        self.name = name.replace(' ','')
        self.passwd = passwd
        self.domain = domain
        
    def getUserName(self):
        return self.name
    
    def getUserPasswd(self):
        return self.passwd

    def getDomain(self):
        return self.domain
    
    def getLocalUser(self):
        return StoreInfoParser.instance().getUser()
    
    def saveLocalUser(self, name):
        StoreInfoParser.instance().setUser(name)
    
    def getUserServer(self):
        serverUrl = StoreInfoParser.instance().getCurrenCenter()
        tmp = serverUrl.split(":")
        num = len(tmp)
        if num > 1:
                serverUrl = tmp[0] + ":" + tmp[1]
        if num > 2:
            if tmp[2] == "true":
                    self.ssl = True
            else:
                    self.ssl = False
        else:
            self.ssl = False
        return serverUrl
    
    def cancelLocalUser(self):
        StoreInfoParser.instance().setUser("")
    
    def isFixedCenterVersion(self):
        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()"))
    
        request = QNetworkRequest() 
        config = QSslConfiguration() 
    
        config.setPeerVerifyMode(QSslSocket.VerifyNone)
        config.setProtocol(QSsl.TlsV1)
        request.setSslConfiguration(config)
    
        if self.ssl:
            http = "https"
        else:
            http = "http"
        strUrl = http + "://" + self.serverUrl + "/api"
        request.setUrl(QUrl(strUrl))
        request.setRawHeader("Authorization", "Basic " + QByteArray(QString("%1:%2").arg(self.name + "@" + self.domain).arg(self.passwd).toAscii()).toBase64())
       
        request.setRawHeader("Filter", "true")
        # QNetworkReply* 
        reply = netMgmt.get(request)
        t.start(timeout)
        eventLoop.exec_()
        vmInfo = reply.readAll()
        reply.deleteLater()
        if (vmInfo.contains("<full_version>")):
            return True
        else:
            return False
    
    #读取文件，确定用户是否设置自动登录
    def isAuto(self):
        #读取自动登录文件
        ui = StoreInfoParser.instance().getLoginSet()
        if len(str)>0:
            user_info = ui.split(",")
            self.updateUserInfo(user_info[0], user_info[1], user_info[2])
            return True
        return False
    
        #获取默认登录的虚拟机
    def getDefaultVm(self):
        #读文件，显示默认登录的虚拟机
        return StoreInfoParser.instance().getDefaultVM()
    
    def setDefaultVm(self,vmid):
        StoreInfoParser.instance().setdefaultvm(vmid)
    
    #获取usb设置，看是否自动透传usb设备
    def getUsbSet(self):
        return StoreInfoParser.instance().getUsbSet()
    
    def toList(self,listStr):
        listT = []
        listS = "a"
        if type(listStr) == type(listS):
            if listStr == "" or listStr == "None" or listStr == "[]":
                return []
            else:
                listList = []
                lst = listStr.split(",")
                for i in range(len(lst)):
                    listList.append(lst[i].split("'")[1])
                return listList
        elif type(listStr) == type(listT):
            return listStr  
        return []

    def getTerminalId(self):
        currentCenter = self.getUserServer()
        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):
        currentCenter = self.getUserServer()
        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 getTerminalName(self):
        return StoreInfoParser.instance().getTerminalName()
        
    def setTerminalName(self,name):
        StoreInfoParser.instance().setTerminalName(name)
    
    def getTerminalStatus(self):
        return StoreInfoParser.instance().getTerminalStatus()
        
    def setTerminalStatus(self,terminalstatus):
        StoreInfoParser.instance().setTerminalStatus(terminalstatus)

    def getPersonalDisk(self):
        if not self.personalDisks:
            from offline.net.OfflineNetUtil import OfflineNetUtil
            net = OfflineNetUtil()
            self.personalDisks = net.requestPersonalDisk()
        
        from setting.logrecord import LogRecord
        LogRecord.instance().logger.info('%s Personal Disk:%s'%(self.name, self.personalDisks))
        print (self.personalDisks)
        return self.personalDisks
    
    def clearPersonalDisk(self):
        self.personalDisks = None
    
    @classmethod 
    def instance(cls):
        if (cls._instance == None):
            cls._instance = User()
        return cls._instance
    
    
