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

from PyQt4.QtCore import QObject, QProcess
import os
import time
import requests 
import json
from networkmanager import NetworkManager
from vminfomanager import VMInfoManager
import common 
from configFileParser import ConfigFileParser
from storeinfoparser import StoreInfoParser
from windowMonitor import WindowMonitor
from logrecord import LogRecord
import globalfunc
import requestinfo
import globalvariable



class VMOperation(QObject):
    _instance = 0 
    def __init__(self):
        super(VMOperation,self).__init__()
        self.curVMInfo = []
        
    @classmethod 
    def instance(cls):
        if (cls._instance == 0):
            cls._instance = VMOperation()
            
        return cls._instance
    
    def setCurrentVMInfo(self, vmInfo):
        self.curVMInfo = vmInfo
        if vmInfo.has_key("vmname"):
            self.vmName = vmInfo["vmname"]
        else:
            self.vmName = globalvariable.CLASS_STATUS_VM_NAME
        
    def openVM(self, refresh=False):
        """打开虚拟机"""
        self.refreshCurrentVMInfo()
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        resolutionValue = StoreInfoParser.instance().getResolutionValue()
        studentName = StoreInfoParser.instance().getTerminalName()
        width = "1024"
        height = "768"
        redirectonconnect = "0x03,-1,-1,-1,0|-1,-1,-1,-1,1"
        if resolutionValue:
            width = resolutionValue.split("x")[0]
            height = resolutionValue.split("x")[1]

        if self.curVMInfo["state"] == "running":
            port = self.curVMInfo["graphics"]["port"]
            argcList = ["smep://%s/?port=%s" % (serverIp, port), "-f", "--vmname=%s" % self.vmName, "--serverip=%s" % serverIp, "--width=%s" % width, "--height=%s" % height, "--student_name=%s"%studentName, "--smep-usbredir-redirect-on-connect=%s" % redirectonconnect ]

            if port:
                LogRecord.instance().logger.info(u"开始启动window进程")
                os.system("pkill window")
                QProcess.startDetached("/usr/massclouds/vdi/client/window/window", argcList);
            return True
        else:
            if self.curVMInfo["state"] == "shutoff" or self.curVMInfo["state"] == "shutdown":
                LogRecord.instance().logger.info(u"开始启动当前选择的虚拟机")
                self.controlVM("startVMThread")
                time.sleep(3)

            for j in range(60):
                if self.refreshCurrentVMInfo():
                    if self.curVMInfo["state"] == "running":
                        port = self.curVMInfo["graphics"]["port"]
                        serverIp = StoreInfoParser.instance().getCloudsServerIP()
                        argcList = ["smep://%s/?port=%s" % (serverIp, port), "-f", "--vmname=%s" % self.vmName, "--serverip=%s" % serverIp, "--width=%s" % width, "--height=%s" % height, "--student_name=%s"%studentName, "--smep-usbredir-redirect-on-connect=%s" % redirectonconnect]

                        if port:
                            LogRecord.instance().logger.info(u"开始启动window进程")
                            os.system("pkill window")
                            QProcess.startDetached("/usr/massclouds/vdi/client/window/window", argcList)
                        return True
                    else:
                        self.controlVM("startVMThread")
                        time.sleep(10)

                LogRecord.instance().logger.info(u"启动当前选择的虚拟机失败，失败次数%s" % str(j))
    #             return False

            LogRecord.instance().logger.info(u"启动当前选择的虚拟机失败")
        return False
    
    def slotOpenVM(self, refresh=False):
        """打开虚拟机"""
        self.refreshCurrentVMInfo()
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        resolutionValue = StoreInfoParser.instance().getResolutionValue()
        studentName = StoreInfoParser.instance().getTerminalName()
        width = "1024"
        height = "768"
        redirectonconnect = "0x03,-1,-1,-1,0|-1,-1,-1,-1,1"
        if resolutionValue:
            width = resolutionValue.split("x")[0]
            height = resolutionValue.split("x")[1]

        if self.curVMInfo["state"] == "running":
            port = self.curVMInfo["graphics"]["port"]
            argcList = ["smep://%s/?port=%s" % (serverIp, port), "-f", "--vmname=%s" % self.vmName, "--serverip=%s" % serverIp, "--width=%s" % width, "--height=%s" % height, "--student_name=%s"%studentName, "--smep-usbredir-redirect-on-connect=%s" % redirectonconnect ]

            if port:
                LogRecord.instance().logger.info(u"开始启动window进程")
                os.system("pkill window")
                QProcess.startDetached("/usr/massclouds/vdi/client/window/window", argcList);
            return True
        else:
            if self.curVMInfo["state"] == "shutoff" or self.curVMInfo["state"] == "shutdown":
                LogRecord.instance().logger.info(u"开始启动当前选择的虚拟机")
                self.controlVM("startVMThread")
                time.sleep(3)

            for j in range(60):
                if self.refreshCurrentVMInfo():
                    if self.curVMInfo["state"] == "running":
                        port = self.curVMInfo["graphics"]["port"]
                        serverIp = StoreInfoParser.instance().getCloudsServerIP()
                        argcList = ["smep://%s/?port=%s" % (serverIp, port), "-f", "--vmname=%s" % self.vmName, "--serverip=%s" % serverIp, "--width=%s" % width, "--height=%s" % height, "--student_name=%s"%studentName, "--smep-usbredir-redirect-on-connect=%s" % redirectonconnect]

                        if port:
                            LogRecord.instance().logger.info(u"开始启动window进程")
                            os.system("pkill window")
                            QProcess.startDetached("/usr/massclouds/vdi/client/window/window", argcList)
                        return True
                    else:
                        self.controlVM("startVMThread")
                        time.sleep(2)

                LogRecord.instance().logger.info(u"启动当前选择的虚拟机失败，失败次数%s" % str(j))

            LogRecord.instance().logger.info(u"启动当前选择的虚拟机失败")
        return False
    
    def autoCloseVMLesson(self):
        vmIdList = WindowMonitor.instance().getProcessIDList()
        
        if vmIdList:
            for ID in vmIdList:
                LogRecord.instance().logger.info(u"自动关闭相应的window窗口")
                os.system("kill -9 %s" % ID)
        os.system("pkill window")

    def controlVM(self, action):
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return

        url = "https://%s:8001/vms/%s/%s" % (serverIp, self.vmName, action)
        if not requestinfo.Requests.instance().postRequestInfo(url):
            LogRecord.instance().logger.info(u"控制虚拟机操作失败")


    def createVMLesson(self, paramInfo):
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return

        ip = globalfunc.get_ip_address()
        mac = globalfunc.get_mac_address()
        course = paramInfo['name']
        uuidValue = paramInfo['name']
        paramInfo['name'] = uuidValue
        payload = {'uuid': uuidValue, "course":course, "ip":ip, "mac":mac}

        url = "https://%s:8001/clouddesktops" % serverIp

        v = requestinfo.Requests.instance().postRequestInfo(url, payload, True)
        LogRecord.instance().logger.info(u'aaaaa！')
        return v["name"] if v is not False else None


    def removeVMLesson(self, vmName):
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return False
        mac = globalfunc.get_mac_address()
        payload = {'deletevm':'', "name":vmName, "mac":mac}
        url = "https://%s:8001/clouddesktops" % serverIp

        if not requestinfo.Requests.instance().postRequestInfo(url, payload):
            return False
        return True
    
    def refreshCurrentVMInfo(self):
        vmInfo = NetworkManager.instance().getVMInfo(self.vmName)
        if vmInfo == None:
            return
        if len(vmInfo) == 0:
            return
        if vmInfo:
            self.curVMInfo = vmInfo[0]
            return True
         
        LogRecord.instance().logger.info(u"获取并刷新虚拟机信息失败")
        return False
       
    def refreshCurrentVMInfoBack(self):
        if globalvariable.CLASS_STATUS_VM_NAME !=None and globalvariable.CLASS_STATUS_VM_NAME != self.vmName:
            self.curVMInfo["state"] = "shutoff"
            #self.curVMInfo["graphics"]["port"] = "port"
            LogRecord.instance().logger.info(u"获取并刷新虚拟机信息失败")
            return False
            
        vmPort = NetworkManager.instance().getVMPort(self.vmName)
        if vmPort == None:
            self.curVMInfo["state"] = "shutoff"
            #self.curVMInfo["graphics"]["port"] = "port"
            LogRecord.instance().logger.info(u"获取并刷新虚拟机信息失败")
            return False
        elif type(vmPort) == type(555):
            self.curVMInfo["state"] = "running"
            self.curVMInfo["graphics"]["port"] = str(vmPort)
            LogRecord.instance().logger.info(u"获取并刷新虚拟机信息成功")
            return True
            
        else:
            self.curVMInfo["state"] = "shutoff"
            #self.curVMInfo["graphics"]["port"] = "port"
            LogRecord.instance().logger.info(u"获取并刷新虚拟机信息失败")
            return False
        
        
        
        
        