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

from PyQt4.QtCore import QObject
from model.request.httprequest import HttpRequests
from common import commondata
from model.infomodel.userinfo import LoginUserInfo

class HttpRequestsUtility(QObject):
    _instance = 0
    def __init__(self):
        super(HttpRequestsUtility,self).__init__()
        baseInfo = LoginUserInfo.instance().getUserInfo()
        self.serverIp = baseInfo.serverIp
        self.request = HttpRequests()


    def getServerIp(self):
        baseInfo = LoginUserInfo.instance().getUserInfo()
        return baseInfo.serverIp
    
    def getUsersInfo(self, tenantName):
        url = commondata.GET_USER_INFO_PATH
        userInfoMap = self.getRequestInfo(url, tenantName)
        if userInfoMap == "ConnectionError": return "ConnectionError"
        if userInfoMap: return userInfoMap
            
        return userInfoMap
    
    def updateUserInfo(self, userName, newPassword):
        tenantList = self.getTenantsListInfo()
        if tenantList is None or tenantList == "ConnectionError":
            return tenantList
        
        for tenant in tenantList["tenants"]:
            usersInfo = self.getUsersInfo(tenant["name"])
            
            if usersInfo == "ConnectionError" or usersInfo == "forbidden" or usersInfo is None: 
                return usersInfo
        
            userInfo = [user["id"] for user in usersInfo["users"] if user["username"] == userName]
            if userInfo:
                return self.changeUserInfo(tenant["name"], userInfo[0], newPassword)
            
        return False

        
    def changeUserInfo(self, tenantName, userId, password):
        url = commondata.GET_USER_LIST_INFO_PATH  % (userId,)
        userinfo = {
                        "user": {
#                             "name": "zll",
#                             "email": "john.smith@example.org",
#                             "enabled": True,
                            "password": password,
                        }
                    }
        return self.putRequest(url, userinfo, tenantName)
        
    def getVMSDetailsInfo(self, tenantName, tenantId):
        url = commondata.GET_VMS_DETAIL_PATH  % (tenantId, )
        return self.getRequestInfo(url, tenantName)
    
    def getVMDetailsInfo(self, tenantName, tenantId, vmId):
        url = commondata.GET_VM_DETAIL_PATH  % (tenantId, vmId, )
        return self.getRequestInfo(url, tenantName)
        
    def getFlavorsInfo(self, tenantName, tenantId):
        url = commondata.GET_FLAVORS_DETAIL_PATH  % (tenantId, )
        return self.getRequestInfo(url, tenantName)
    
    def getFlavorsDetailsInfo(self, tenantName, tenantId, flavorId):
        url = commondata.GET_FLAVOR_DETAIL_PATH  % (tenantId, flavorId, )
        return self.getRequestInfo(url, tenantName)
    
    def getImagesInfo(self, tenantName, tenantId):
        url = commondata.GET_IMAGES_DETAIL_PATH  % (tenantId, )
        return self.getRequestInfo(url, tenantName)
    
    def getTenantsListInfo(self):
        url = commondata.GET_TENANTS_PATH
        return self.getRequestInfo(url)
    
    def getVMPortInfo(self, tenantName, tenantId, vmId):
        url = commondata.GET_VM_PORT_INFO  % (tenantId, vmId, )
        actionData = {
                        "os-getSPICEConnectInfo": {"type": "spice-html5"},
                            }       
        
        return self.postRequest(url, actionData, tenantName, isNeedReturnValue=True)
    
        
    def getRequestInfo(self, url, tenantName=None):
        rquestInfo = self.request.getRequestInfo(url, tenantName)
        return rquestInfo
        
    def getNecessaryInfoByTenant(self, tenantName, tenantId):
        vmDetailInfo = self.getVMSDetailsInfo(tenantName, tenantId)
        flavorsInfo = self.getFlavorsInfo(tenantName, tenantId)
        imagesInfo = self.getImagesInfo(tenantName, tenantId)
        
        if vmDetailInfo == "ConnectionError" or flavorsInfo == "ConnectionError" or imagesInfo == "ConnectionError":
            return "ConnectionError"
        
        if vmDetailInfo is None or flavorsInfo is None or imagesInfo is None:
            return []
        
        return [vmDetailInfo, flavorsInfo, imagesInfo, tenantName, tenantId]
    
    def getAllNecessaryInfo(self):
        tenantList = self.getTenantsListInfo()
        if tenantList is None or tenantList == "ConnectionError":
            return tenantList

        infoList = []
        for tenant in tenantList["tenants"]:
            info = self.getNecessaryInfoByTenant(tenant["name"], tenant["id"])
            if info == "ConnectionError": return "ConnectionError"
            if info: infoList.append(info)
    
        return infoList
    
    def operateVMAction(self, action, vmId, tenantName, tenantId):
        if action == "shutDown":
            return self.shutDownVM(vmId, tenantName, tenantId)
        elif action == "reboot":
            return self.rebootVM(vmId, tenantName, tenantId)
        elif action == "start":
            return self.startVM(vmId, tenantName, tenantId)
    
    def shutDownVM(self, vmId, tenantName, tenantId):
        url = commondata.POST_VM_ACTION % (tenantId, vmId, )
        actionData = {
                        "os-stop": "null",
                            }       
        
        return self.postRequest(url, actionData, tenantName)
    
    def startVM(self, vmId, tenantName, tenantId):
        url = commondata.POST_VM_ACTION % (tenantId, vmId, )
        actionData = {
                        "os-start": "null",
                            }       
        
        return self.postRequest(url, actionData, tenantName)
    
    def rebootVM(self, vmId, tenantName, tenantId):
        url = commondata.POST_VM_ACTION % (tenantId, vmId, )
        actionData = {
                        "reboot": {
                                "type": "SOFT"
                                            }
                            }       
        
        return self.postRequest(url, actionData, tenantName)
    
    def postRequest(self, url, data, tenantName, isNeedReturnValue=False):
        rquestInfo = self.request.postRequestInfo(url, data, tenantName, isNeedReturnValue)
        return rquestInfo
    
    
    def putRequest(self, url, data, tenantName, isNeedReturnValue=False):
        rquestInfo = self.request.putRequestInfo(url, data, tenantName, isNeedReturnValue)
        return rquestInfo
        
        
    