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

from PyQt4.QtCore import QObject, QProcess, QStringList, QString
from model.request.httprequestutility import HttpRequestsUtility
from httprequestinfoparser import HttpRequestsInfoParser
from model.infomodel.userinfo import LoginUserInfo
import time
from common import commondata
from common import globalfun
from model.cfg.storeinfoparser import StoreInfoParser

class UtilityRequestOperationWrap(QObject):
    _instance = 0
    def __init__(self):
        super(UtilityRequestOperationWrap,self).__init__()
        self.errorInfoMap = {"vmDetailInfoError": u"获取云主机信息失败",
                             "portInfoError": u"获取端口信息失败",
                             "openVmFailedError": u"执行打开云主机操作失败！",
                             "ConnectionError": "ConnectionError",
                             "startVmFailedError": u"云主机启动失败！"
                             }
    
    def checkloginAuth(self):
        return self.getAllVMNecessaryInfo()
    
    def getAllVMNecessaryInfo(self):
        utility = HttpRequestsUtility()
        infoList = utility.getAllNecessaryInfo()
        if infoList == None or infoList == "ConnectionError":
            return infoList

        vmBaseInfoList = HttpRequestsInfoParser.vmJsonDataParser(infoList)
        return vmBaseInfoList
    
    def getVMListInfo(self):
        return self.getAllVMNecessaryInfo()
    
    def changeUserPassword(self, userName, newPassword):
        utility = HttpRequestsUtility()
        return utility.updateUserInfo(userName, newPassword)
    
    def getFlavorDetailInfo(self, tenantName, tenantId, flavorId):
        utility = HttpRequestsUtility()
        flavorInfo = utility.getFlavorsDetailsInfo(tenantName, tenantId, flavorId)
        if flavorInfo == None or flavorInfo == "ConnectionError":
            return flavorInfo
        
        return HttpRequestsInfoParser.flavorJsonDataParser(flavorInfo)
    
    def execVMAction(self, action, VMId, tenantName, tenantId):
        utility = HttpRequestsUtility()
        return utility.operateVMAction(action, VMId, tenantName, tenantId)
    
    def getVMPortInfo(self, tenantName, tenantId, VMId):
        utility = HttpRequestsUtility()
        portInfo = utility.getVMPortInfo(tenantName, tenantId, VMId)
        if portInfo == None or portInfo == "ConnectionError":
            return portInfo
        
        console = portInfo.get("console", None)
        if console:
            ip = console.get("host", None)
            port = console.get("port", None)
            if ip and port:
                return (ip, port)
        
        return None
    
    def checkVMStatus(self, action, VMId, tenantName, tenantId):
        utility = HttpRequestsUtility()
        
        for i in range(30):
            vmDetailInfo = utility.getVMDetailsInfo(tenantName, tenantId, VMId)
            if vmDetailInfo == "ConnectionError": return "ConnectionError"
            if vmDetailInfo == None:
                return self.errorInfoMap["vmDetailInfoError"]
            
            vmStatue = vmDetailInfo["server"]["status"]
            if action == "shutDown" and vmStatue == "SHUTOFF":
                return True
            
            if action == "reboot" and vmStatue == "ACTIVE":
                return True
            
            time.sleep(6)
        
        return True
    
    def openVM(self, VMId, tenantName, tenantId):
        utility = HttpRequestsUtility()
        vmDetailInfo = utility.getVMDetailsInfo(tenantName, tenantId, VMId)
        if vmDetailInfo == "ConnectionError": return "ConnectionError"
        if vmDetailInfo == None:
            return self.errorInfoMap["vmDetailInfoError"]
        
        if vmDetailInfo["server"]["status"] == "ACTIVE":
            vmInfo = self.getVMPortInfo(tenantName, tenantId, VMId)
            if vmInfo == "ConnectionError": return "ConnectionError"
            if vmInfo == None:
                return self.errorInfoMap["portInfoError"]
            return self.openSpiceClient(vmInfo[0], vmInfo[1])
            
        if utility.operateVMAction("start", VMId, tenantName, tenantId) is not True:
            return self.errorInfoMap["openVmFailedError"]
        
        for i in range(3):
            vmDetailInfo = utility.getVMDetailsInfo(tenantName, tenantId, VMId)
            if vmDetailInfo["server"]["status"] == "ACTIVE":
                vmInfo = self.getVMPortInfo(tenantName, tenantId, VMId)
                if vmInfo == "ConnectionError": return "ConnectionError"
                if vmInfo == None:
                    return self.errorInfoMap["portInfoError"]
                return self.openSpiceClient(vmInfo[0], vmInfo[1])
            time.sleep(3)
            
        return self.errorInfoMap["startVmFailedError"]
        
    def openSpiceClient(self, ip, port):
        if port is None:
            return False
        
        argList = []
        resolution = []
        cmd = QString("smep://%s/?port=%s" % (ip, port))
        
        monitorsList = globalfun.getActiveMonitors()
        flag,tempValue = globalfun.isMultiConnect()
        if len(monitorsList) > 1 and flag:
            width = QString("--width=") + tempValue.split("x")[0]
            height = QString("--height=") + tempValue.split("x")[1]
            resolution.append(width)
            resolution.append(height)
             
        argList.append(cmd)
        argList.append(QString("-f"))
        
        if resolution:
            argList.append(resolution[0])
            argList.append(resolution[1])
            
        if StoreInfoParser.instance().getAutoVmScreenState() == "yes":
            argList.append("--toolbar=hide")
            
        return QProcess.startDetached(commondata.WINDOW_CMD_NAME, QStringList(argList))
        
        