#!/usr/bin/python
#coding=utf-8

import os, sys

from threading import Thread
from Queue import Queue,Empty
from os import getenv,system
from PyQt4.QtCore import SIGNAL, SLOT, Qt, QString, QEvent,pyqtSlot,QEventLoop
from PyQt4.QtGui import QPalette,QBrush, QDesktopWidget

from threading import Lock      # 导入线程锁
from logger.logrecord import LogRecord

from validate.userValidate import UserValidate
from validate.vmlist import VmList
from validate.agentInfo import AgentInfo


class OperatorVMCmd(object):
    '''OperatorVMCmd'''

    __OperatorVMCmdMutex =  Lock()      # 锁
    __request_queue = None
    __respond_queue = None

    __userValidate  = None
    __vmList        = None
    __agentInfo     = None


    # 登录
    @classmethod
    def loginCenterCmd(cls,userName,password,CenterIP):

        userInfo = {
                    "userName"      : userName,
                    "userPassword"  :  password
        }

        cls.__userValidate  =  UserValidate(userInfo,CenterIP)
        cls.__vmList        =  VmList(userInfo,CenterIP)
        cls.__agentInfo     =  AgentInfo(userInfo,CenterIP)

        try:
            '''loginCenterCmd'''
            loginEventLop = QEventLoop()
            res = None
            recvMsg = {
                "login" : None
            }
            status = { "status":"MCOS_LOGIN_FAILD",
                        "info" : "",
                        "flag" : ""
                       }
            result = {  "vmInfoList":[],
                        "agentInfo":[],
                        "appInfoList":[],
                        }

            # =====================  子线程函数体　=====================
            #  接收请求响应
            def FuncQueuGet():
                try:
                    while True:
                        # 接收
                        LogRecord.instance().logger.info("[info]: login陆。。。")  # 日志
                        res1 = cls.__userValidate.login()
                        print "[info]---s------------  ",res1[0],res1[1]
                        if res1[0] == True:
                            status["status"] = "MCOS_LOGIN_SECCESS"
                        else:
                            status["status"] = "MCOS_LOGIN_FAILD"
                            status["info"] = res1[1]
                            LogRecord.instance().logger.info("[info]: login陆失败"+str(res1[1]))  # 日志
                            break

                        LogRecord.instance().logger.info("[info]: getVMlist")  # 日志
                        # 请求 虚拟机 列表
                        res2 = cls.__vmList.getVMlist()
                        if res2[0] == True:
                            status["status"] = "MCOS_LOGIN_SECCESS"
                            result["vmInfoList"] = res2[1]
                        else:
                            # status["status"] = "MCOS_LOGIN_FAILD"
                            status["status"] = "MCOS_LOGIN_SECCESS"
                            status["info"] = res2[1]
                            info =  "获取虚拟机列表失败:" + str(res2[1])
                            LogRecord.instance().logger.warn(info)  # 日志
                            # break
                        #  获取 应用 列表
                        LogRecord.instance().logger.info("[info]: 获取应用列表")  # 日志
                        res3 =  cls.__agentInfo.getApplist()
                        if res3[0] == True:
                            status["status"] = "MCOS_LOGIN_SECCESS"
                            # if len(res3[1]) == 0:  # 如果应用列表为空
                            #     break
                            if type(res3[1]) == type([]):
                                result["appInfoList"] = res3[1]
                                if (len(res3[1]) == 0):
                                    break                   # app list is empty ;
                            #
                        else:
                            # status["status"] = "MCOS_LOGIN_FAILD"
                            # status["info"] = res3[1]

                            status["status"] = "MCOS_LOGIN_FAILD"
                            status["info"] = "",
                            status["flag"] = "获取应用列表失败"

                            LogRecord.instance().logger.info("[info]: 获取应用列表失败")  # 日志
                            break

                        LogRecord.instance().logger.info("[info]: 下载应用图标")  # 日志
                        cls.__agentInfo.downloadAppIcons()

                        res4 = cls.__agentInfo.getAgentInfo()
                        if res4[0] == True:
                            status["status"] = "MCOS_LOGIN_SECCESS"
                            result["agentInfo"] = res4[1]
                        else:
                            status["status"] = "MCOS_LOGIN_FAILD"
                            status["info"] = res4[1]
                            break

                        break
                except Exception as e:           # 处理异常
                    LogRecord.instance().logger.info("[inf]:",str(e.message))  # 日志
                    # print e.message
                    status["status"] = "MCOS_LOGIN_FAILD"
                finally:
                    while not loginEventLop.isRunning():    # 等待父线程，执行到 loginEventLop.exec_()
                        pass
                    loginEventLop.quit()
            #  ===================== 子线程函数体 end  ====================

            threadQueueGet = Thread(target=FuncQueuGet)  # 初始化接收线程
            threadQueueGet.setDaemon(True)
            threadQueueGet.start()   # 启动接收线程

            loginEventLop.exec_()    # 进入qt事件循环  防止界面卡顿，事件

            # 处理返回值
            if status["status"] == "MCOS_LOGIN_SECCESS":
                vmInfoList  = result["vmInfoList"]
                agentInfo   = result["agentInfo"]
                appInfoList = result["appInfoList"]

                return (vmInfoList,agentInfo,appInfoList)

            elif status["status"] == "MCOS_LOGIN_FAILD":
                raise Exception(status["info"])
            else:
                print "loginCenterCmd : ", recvMsg["login"][0]
                raise Exception("Login Timeout")
        finally:
            # print ""
            pass

    # 登录
    @classmethod
    def logoutCenterCmd(cls,userInfo=None):
        from time import sleep


        try:
            loginEventLop = QEventLoop()
            status = {"state":False,
                      "info" :""}

            #res = None
            # =====================  子线程函数体　=====================
            #  接收请求响应
            def FuncQueuGet():
                try:
                    # cnt = 0
                    # while cnt < 15:
                    #     cnt = cnt + 1
                    #     res = cls.__userValidate.logout()
                    #     if res[0] == True:
                    #         print "             注销成功"
                    #
                    #         sleep(0.2)
                    #         res2 = cls.__userValidate.sessionIsLogout()
                    #         if res2[0] == True:
                    #             break
                    #     else:
                    #         print res[0]
                    #     sleep(0.1)

                    res = cls.__userValidate.logout()
                    status["state"]= res[0]
                    status["info"]= res[1]
                finally:
                    while not loginEventLop.isRunning():    # 等待父线程，执行到 loginEventLop.exec_()
                        pass
                    loginEventLop.quit()
            #  ===================== 子线程函数体 end  ====================

            threadQueueGet = Thread(target=FuncQueuGet)  # 初始化接收线程
            threadQueueGet.setDaemon(True)
            threadQueueGet.start()   # 启动接收线程

            loginEventLop.exec_()    # 进入qt事件循环  防止界面卡顿，事件
            return status["state"],status["info"]
        except Exception as e:
            return False, "注销异常"
        finally:
            pass

    @classmethod
    def getVmList(cls):  # 获取虚拟机列表
        res = cls.__vmList.getVMlist()
        if res[0] == True:
            return res
        else :
            return False,res[1]

    #########################################################
    # 进入虚拟机
    #########################################################
    @classmethod
    def interVMCmd(cls,userInfo,vmInfo,request_queue,respond_queue,):
        try:
            sndMsg = ["MCOS_ENTERVM",userInfo,vmInfo]

            print cls.__doc__, "  send ------->  ", sndMsg
            request_queue.put(sndMsg, 0)

            loginEventLop = QEventLoop()
            recvMsg = {}
            # ----------------- 子线程函数体　------------------
            #  接收请求响应
            def FuncQueuGet():
                try:
                    pass
                    recvMsg["login"] = respond_queue.get(1, 90)  # 超时2秒
                    print recvMsg
                except Empty:  # 处理超时异常
                    recvMsg["login"] = ["TimeOut"]
                finally:
                    while not loginEventLop.isRunning():  # 等待父线程，执行到 loginEventLop.exec_()
                        pass
                    loginEventLop.quit()
            # ---------------------子线程函数体 end---------------
            threadQueueGet = Thread(target=FuncQueuGet)  # 初始化接收线程
            threadQueueGet.setDaemon(True)
            threadQueueGet.start()  # 启动接收线程
            loginEventLop.exec_()  # 进入qt事件循环  防止界面卡顿，事件
        finally:
            pass


    # 获取虚拟机状态
    @classmethod
    def changePasswdCmd(cls,userInfo,passwdInfo,request_queue=None,respond_queue=None):

        sndMsg = ["MCOS_CHANGEPASSWD",userInfo,passwdInfo]


        loginEventLop = QEventLoop()
        recvMsg = {
            "msgState":"",
            "MCOS_VMSTATE":""
        }
        # ----------------- 子线程函数体　------------------
        #  接收请求响应
        def FuncQueuGet():
            try:
                pass
                # recvMsg["MCOS_VMSTATE"] = cls.__respond_queue.get(1, 15)  # 超时2秒
            except Empty:  # 处理超时异常
                recvMsg["msgState"] = "TimeOut"
            finally:
                while not loginEventLop.isRunning():  # 等待父线程，执行到 loginEventLop.exec_()
                    pass
                loginEventLop.quit()
        # ---------------------子线程函数体 end---------------
        threadQueueGet = Thread(target=FuncQueuGet)  # 初始化接收线程
        threadQueueGet.setDaemon(True)
        threadQueueGet.start()  # 启动接收线程
        loginEventLop.exec_()  # 进入qt事件循环  防止界面卡顿，事件

        if recvMsg["msgState"] == "TimeOut":
            print "getVMstateCmd   TimeOut"
            return False,"TimeOut"
        elif recvMsg["MCOS_VMSTATE"][0] == "MCOS_CHANGEPASSWD_SECCESS":
            print "change password seccess"
            return True,""
        elif recvMsg["MCOS_VMSTATE"][0] == "MCOS_GETPASSWDLEVEL_FAILD":
            print "change password faild"
            return False,recvMsg["MCOS_VMSTATE"][1]
        elif recvMsg["MCOS_VMSTATE"][0] == "MCOS_GETPASSWDLEVEL_ERR":
            return False,recvMsg["MCOS_VMSTATE"][1]
        else:
            print "getVMstateCmd   FAILE"
            return False




######################################################################################
#/mcos/dvclient/window/window --spice-ca-file=/mcos/dvclient/cfg/.smep/smep_ca.pem  spice://server27.com/?tls-port=5900

# cmd = "/mcos/dvclient/window/window --spice-ca-file=/mcos/dvclient/cfg/.smep/smep_ca.pem  "
# spiceCmd = "spice://server27.com/?tls-port=5900"
# system(cmd + spiceCmd)

######################### test ##############################
# import os
# from os import getenv
# print  getenv('MCOS_DESKTOP_RDP_DEBUG')
# if "DESKTOP_RDP_DEBUG_ON" == getenv('MCOS_DESKTOP_RDP_DEBUG'): # 读取环境变量 图片路径
#     pid = os.fork()
#     if pid == 0:
#         ''' child press '''
#         from os import environ          # 环境变量
#         environ["LD_LIBRARY_PATH"] = "/mcos/dvclient/lib/"
#         # os.execl("/home/jxm/freerdp-0.7.0/X11/xfreerdp","xfreerdp","-u","jxm","-p","meiyoumima", "-g", "1280x800",
#         #
#         os.execl("/mcos/dvclient/window/window","window","--spice-ca-file=/mcos/dvclient/cfg/.smep/smep_ca.pem",
#                  "spice://server27.com/?tls-port=5900")
#         exit(0)
#     else:
#         pass
#========================= test end ==========================
# ----------------- 子线程函数体　------------------
#  接收请求响应