# coding:utf-8
import os
import time
import thread
import threading
import Queue
from os import getenv

from rdp_py.XFRDP import XFRDP
from logger.logrecord import LogRecord

class AppRDP():
    """
    rdp相关操作，包括建立连接，断开连接，发送消息，接受消息，显示rdp窗口，隐藏rdp窗口
    """
    def __init__(self,user_,backToPannel_):
        self.envPath=getenv('LD_LIBRARY_RDP_PATH')
        self.user=user_
        self.backToPannel=backToPannel_
        LogRecord.instance().logger.debug("AppRDP初始化！")
        self.fullScreen=True
        self.rdpWidth='1024'
        self.rdpHeight='768'
        self.rdpColor='16'
        libPath=''
        if (self.envPath == '') or (self.envPath == None):
            libPath=os.path.abspath('.')
            libPath+='/uiWindow/VirtApp/rdp_py/lib64/libxfreerdp-client.so'
            # print(libPath)
        else:
            libPath=self.envPath
            libPath+='/lib64/libxfreerdp-client.so'
        self.rdp=XFRDP(libPath)
        self.msgToClientQueue=Queue.Queue()
        self.msgLock=thread.allocate_lock()
        self.isConnected=False
        self.isShowing=False

        #self.user=AppUser(r'www10.com\wang')
        #self.user.setPassword('123456')
        #self.user.setAgentIP('192.168.102.37')
        #self.user.setAgentPort('3389')
        #self.user.setRdpState('disconnected')
        #self.user.setLoginState('ready')
        #appObj=AppObject('calculator','100')
        #appObj.setAppCommand('[startApp::C:\\Windows\\system32\\calc.exe]')
        #appObj.setAppEnable(True)


    def setFullScreen(self,fullScreen_):
        self.fullScreen=fullScreen_
    def isFullScreen(self):
        return self.fullScreen
    
    def setWidth(self,width):
        self.rdpWidth=width
    def getWidth(self):
        return self.rdpWidth
    
    def setHeight(self,height):
        self.rdpHeight=height
    def getHeight(self):
        return self.rdpHeight
    
    def setColor(self,color):
        self.rdpColor=color
    def getColor(self):
        return self.rdpColor
    
    def __del__(self):
        self.isConnected=False
    def connectRDP(self):
        """
        建立rdp连接
        """
        if self.user.getRdpState() == 'connecting':
            if self.rdp.callback == self.receiveMessage:
                LogRecord.instance().logger.debug("尝试连接正在连接的rdp会话")
                return True
            else:
                LogRecord.instance().logger.debug("尝试重新连接正在连接的rdp会话")
                self.disconnectRDP()
                time.sleep(1)
        args=''
        args+=' /t:'+self.user.getName()
        args+=' /u:'+self.user.getName()
        args+=' /p:'+self.user.getPassword()
        args+=' /v:'+self.user.getAgentIP()+':'+self.user.getAgentPort()
        args+=' /port:'+self.user.getAgentPort()
        args+=' /bpp:'+self.rdpColor
        if not self.isFullScreen():
            args+=' /size:'+self.rdpWidth+'X'+self.rdpHeight
        else:
            args+=' /f'
        # args+=' /d:www10.com'
        # print args
        if self.rdp.create_connection(self.receiveMessage, args):
            self.user.setRdpState('connecting')
            self.isConnected=True
            msgThread=threading.Thread(target=self.manageMsgFromRDP)
            msgThread.setDaemon(True)
            msgThread.start()
            LogRecord.instance().logger.debug("msgThread started.")
            self.isShowing=True
            return True      
        else:
            self.user.setRdpState('connectfailed')
            LogRecord.instance().logger.warn("连接RDP失败！")
            return False

    def disconnectRDP(self):
        LogRecord.instance().logger.debug("断开RDP连接")
        if self.rdp.disconnect():
            self.user.setRdpState('disconnected')
            self.isConnected=False
            self.isShowing=False
            LogRecord.instance().logger.debug("RDP连接断开成功！")
        else:
            self.user.setRdpState('disconnected')
            LogRecord.instance().logger.warn("RDP连接断开失败！")

    def sendMessage(self,msg):
        if not self.isConnected:
            LogRecord.instance().logger.warn("不能向没有建立连接的RDP发送信息！")
            return False
        if self.rdp.send_command(msg):
            return True
        else:
            LogRecord.instance().logger.warn("向RDP发送信息失败！"+msg)
            return False

    def receiveMessage(self,msg):
        try:
            LogRecord.instance().logger.debug("接收到RDP发送来的信息："+msg.decode('GBK'))
            self.msgToClientQueue.put(msg)
        except Exception,err:
            LogRecord.instance().logger.exception('接受RDP消息失败！')
        return 0
    def showRDPWindow(self):
        self.isShowing=True
        return self.rdp.show_window()

    def hideRDPWindow(self):
        return self.rdp.hide_window()

    def manageMsgFromRDP(self):
        #print 'manageMsgFromRDP'
        while self.isConnected:
            if self.msgToClientQueue.empty():
                time.sleep(0.01)
                continue
            msgToClient=self.msgToClientQueue.get()
            if not isinstance(msgToClient,str):
                LogRecord.instance().logger.warn("RDP返回的信息格式错误！%s"%str(type(msgToClient)))
                continue
            if msgToClient.startswith('[callback::0]'):
                self.user.setRdpState('connected')
                #continue

            elif msgToClient.startswith('[callback::10]'):
                #用户任务栏点击关闭窗口
                self.user.setRdpState('disconnected')
                self.isConnected=False
                #continue

            elif msgToClient.startswith('[callback::9]'):
                if self.rdp.hide_window():
                    #成功隐藏rdp窗口
                    self.isShowing=False
                else:
                    LogRecord.instance().logger.warn("隐藏RDP窗口失败！")

                #continue

            elif msgToClient.startswith('[callback::8]'):
                self.user.setRdpState('connected')
                # if self.showRDPWindow():
                #     #成功显示rdp窗口
                #     pass
                # else:
                #     LogRecord.instance().logger.warn("显示RDP窗口失败！")
                #continue

            elif msgToClient.startswith('[callback::21]'):
                #收起工具栏
                #continue
                pass
            elif msgToClient.startswith('[callback::22]'):
                self.isConnected=False
                #退出消息监听
                #continue

            elif msgToClient.startswith('[callback::30'):
                #rdp连接异常退出
                if self.user.getRdpState() == 'connecting':
                    self.user.setRdpState('connectfailed')
                else:
                    self.user.setRdpState('disconnected')
                self.isConnected=False
                scode=msgToClient[15:]
                try:
                    code=int(scode.split('&&')[0])
                    if code == 2:
                        #判断是否是用户主动退出
                        pass
                    else:
                        #解析退出码，显示退出原因
                        pass
                except Exception,err:
                    LogRecord.instance().logger.exception("rdp异常退出码解析异常！")
                 
                #continue

            elif msgToClient.startswith('[callback::3'):
                #返回应用列表
#                 appNames=msgToClient[15:]
                #continue
                pass
            elif msgToClient.startswith('[callback::25'):
                #返回用于tcp通信的端口号，这里无用
                #continue
                pass
            elif msgToClient.startswith('[callback::100]'):
                #打开应用失败
                LogRecord.instance().logger.warn('打开应用失败!')
                #continue

            elif msgToClient.startswith('[callback::1]'):
                #打开应用成功
                # if self.showRDPWindow():
                #     pass
                # else:
                #     LogRecord.instance().logger.warn('显示rdp窗口失败')
                #continue
                pass

            elif msgToClient.startswith('[HWND::'):
                pass
                #continue
                #传递返回参数给appApplication
            try:
                self.backToPannel(msgToClient)
            except Exception,err:
                LogRecord.instance().logger.exception("backToPannel 异常！")
        self.disconnectRDP()

if __name__ == '__main__':
    appRDP=AppRDP()
    appRDP.setFullScreen(False)
    #import time
    appRDP.connectRDP()
    #time.sleep(10)
    start=time.clock()
    while appRDP.user.getRdpState() != 'connected':
        #print appRDP.user.getRdpState()
        time.sleep(0.01)
    appRDP.sendMessage('[startApp::C:\\Windows\\system32\\calc.exe]')
    appRDP.sendMessage(r'[startApp::C:\Program Files (x86)\Internet Explorer\iexplore.exe]')
    appRDP.sendMessage('[taskbarAll::]')
    print 'start calculator use '+str(time.clock()-start)
    #appRDP.disconnectRDP()