# coding:utf-8
import time

from AppUser import AppUser
from AppObject import AppObject
from AppRDP import AppRDP



# from NotifyWidget import NotifyWedget
# import sys
# from PyQt4 import QtGui
from logger.logrecord import LogRecord


class AppApplication:
    """
    应用相关操作，包括打开应用，关闭应用，展示应用，刷新应用，移动应用，返回面板
    """
    exitCodeDic={1:'强制断开，请重新打开应用！',
              2:'强制注销，请重新打开应用！',
              3:'空闲超时，请重新打开应用！',
              4:'登录超时，请重新打开应用！',
              5:'此用户已在其他设备上登录！',
              6:'内存溢出，请重新打开应用！',
              7:'服务器拒绝连接，请重新打开应用！',
              9:'权限不足，请重新打开应用！',
              101:'主通道解析异常，请重新打开应用！',
              102:'获取文件描述符失败，请重新打开应用！',
              103:'子通道解析异常，请重新打开应用！',
              104:'描述符资源不足，请重新打开应用！',
              106:'网络不稳定，请重新打开应用！',
              107:'检测文件描述符失败，请重新打开应用！',
              108:'子通道发送异常，请重新打开应用！',
              256:'证书异常，请重新打开应用！',#256-266
              4297:'协议异常，请重新打开应用！'}#4297-4501
    def __init__(self,appUser_,eventToPannel_):
        self.user=appUser_
        self.appRDP=AppRDP(self.user,self.backToPannel)
        self.eventToPannel=eventToPannel_

    def __connectRDP(self):
        if self.user.getRdpState() != 'connected':
            conResult=self.appRDP.connectRDP()
            if not conResult:
                LogRecord.instance().logger.debug('连接rdp会话失败')
                self.sendToPannel("startError::5")
                return False
            LogRecord.instance().logger.debug('连接rdp会话')
            self.sendToPannel("startError::0")
        while self.user.getRdpState() != 'connected':
            if self.user.getRdpState() == 'connecting':
                time.sleep(0.1)
                continue
            elif self.user.getRdpState() == 'connectfailed':
               LogRecord.instance().logger.debug('连接rdp会话失败')
               self.user.setRdpState('disconnected')
               self.sendToPannel("startError::3")
               return False
            elif self.user.getRdpState() == 'disconnectfailed':
               LogRecord.instance().logger.debug('断开连接失败,连接rdp会话失败')
               self.user.setRdpState('disconnected')
               self.sendToPannel("startError::4")
               return False
            # conResult=self.appRDP.connectRDP()
            # if not conResult:
            #     LogRecord.instance().logger.debug('连接rdp会话失败')
            #     self.sendToPannel("startError::5")
            #     return False
            # LogRecord.instance().logger.debug('连接rdp会话')
            # self.sendToPannel("startError::0")
        else:
            self.sendToPannel("startError::0")
        return True
        
    def startApp(self,appPosition):
        """
        根据应用的位置打开应用
        """
#         print 'AppApplication startApp start!'
        LogRecord.instance().logger.debug('AppApplication startApp start!')
        appID=self.user.findAppID(appPosition)
        if appID == '':
            LogRecord.instance().logger.debug('找不到应用ID')
            self.sendToPannel("startError::1")
            return False
        appObj=self.user.findAppObjectFromDic(appID)
        if appObj == '':
            LogRecord.instance().logger.debug('找不到应用')
            self.sendToPannel("startError::2")
            return False
        # if self.user.getRdpState() != 'connected':
        #     conResult=self.appRDP.connectRDP()
        #     if not conResult:
        #         LogRecord.instance().logger.debug('连接rdp会话失败')
        #         self.sendToPannel("startError::5")
        #         return False
        #     LogRecord.instance().logger.debug('连接rdp会话')
        #     self.sendToPannel("startError::0")
        # while self.user.getRdpState() != 'connected':
        #     if self.user.getRdpState() == 'connecting':
        #         time.sleep(0.1)
        #         continue
        #     elif self.user.getRdpState() == 'connectfailed':
        #        LogRecord.instance().logger.debug('连接rdp会话失败')
        #        self.user.setRdpState('disconnected')
        #        self.sendToPannel("startError::3")
        #        return False
        #     elif self.user.getRdpState() == 'disconnectfailed':
        #        LogRecord.instance().logger.debug('断开连接失败,连接rdp会话失败')
        #        self.user.setRdpState('disconnected')
        #        self.sendToPannel("startError::4")
        #        return False
        #     # conResult=self.appRDP.connectRDP()
        #     # if not conResult:
        #     #     LogRecord.instance().logger.debug('连接rdp会话失败')
        #     #     self.sendToPannel("startError::5")
        #     #     return False
        #     # LogRecord.instance().logger.debug('连接rdp会话')
        #     # self.sendToPannel("startError::0")
        # else:
        #     self.sendToPannel("startError::0")
        if not self.__connectRDP():
            return False
        LogRecord.instance().logger.debug('发送打开应用命令: '+appObj.getAppCommand())
        sendResult=self.appRDP.sendMessage(appObj.getAppCommand())
        if not sendResult :
            LogRecord.instance().logger.warn('发送打开应用命令失败'+appObj.getAppCommand())
            self.sendToPannel("startError::6")
            return False

    def sendToPannel(self,msg):
        try:
            self.eventToPannel(msg)
        except Exception,err:
            LogRecord.instance().logger.exception("反馈RDP消息异常！断开RDP连接！")
            self.appRDP.disconnectRDP()

    def closeApp(self,appObj):
        pass
    def backHome(self):
        """
        隐藏RDP主窗,隐藏失败就断开RDP连接
        :return:成功/失败
        """
        if self.appRDP.hideRDPWindow():
            self.appRDP.isShowing=False
            return True
        else:
            LogRecord.instance().logger.debug('隐藏RDP主窗口失败!断开RDP连接！')
            self.appRDP.disconnectRDP()
            return False

    def fetchActivities(self):
        """
        获取应用列表
        :return:
        """
        if not self.__connectRDP():
            return
        if self.appRDP.sendMessage('[taskbarAll::]'):
            pass
        else:
            LogRecord.instance().logger.debug('fetchActivities failed!断开RDP连接！')
            self.appRDP.disconnectRDP()

    def alterActivities(self,id,type):
        """
        切换或关闭应用窗口
        :param id:应用窗口
        :param type:切换或关闭
        :return:
        """
        if type == 'activate':
            if self.appRDP.sendMessage('[activityApp::%s]'%id):
                if not self.appRDP.showRDPWindow():
                    LogRecord.instance().logger.debug('show rdp window failed!')

            else:
                LogRecord.instance().logger.debug('activate %s failed!'%id)

        elif type == 'close':
            #关闭应用窗口
            if self.appRDP.sendMessage('[closeAWindow::%s]'%id):
                pass
            else:
                LogRecord.instance().logger.debug('closeWindow %s failed!'%id)

    def showRDP(self):
        if self.appRDP.isShowing:
            if not self.appRDP.showRDPWindow():
                LogRecord.instance().logger.warn("显示RDP窗口失败！")
    def hideRDP(self):
        if self.appRDP.isShowing:
            if not self.appRDP.hideRDPWindow():
                LogRecord.instance().logger.warn("隐藏RDP窗口失败！")
    def displayRDP(self):
        if not self.appRDP.showRDPWindow():
            LogRecord.instance().logger.warn("显示RDP窗口失败！")

    def showAppOnPannel(self,appObj):
        pass
    def refreshApp(self):
        pass
    def moveApp(self,appObj):
        pass
    def backToPannel(self,reason):
        if reason == '':
            LogRecord.instance().logger.debug('message from rdp is empty.')

        else:
            if reason.startswith('[callback::10]'):
                #用户任务栏点击关闭窗口
                pass
            elif reason.startswith('[callback::9]'):
                #没有活动的应用
                self.sendToPannel('noActivities::')

            elif reason.startswith('[callback::8]'):
                #有活动的应用
                self.sendToPannel('aliveActivities::')

            elif reason.startswith('[callback::1]'):
                #有活动的应用
                self.sendToPannel('aliveActivities::')

            elif reason.startswith('[callback::21]'):
                #收起工具栏
                self.sendToPannel('toolUp::')

            elif reason.startswith('[callback::22]'):
                #退出消息监听
                pass
            elif reason.startswith('[callback::30'):
                exitString=reason[15:]
                exitCode=''
                try:
                    exitCode=exitString.split('&&')[0]
                    try:
                        exitNo=int(exitCode)
                        if exitNo >= 256 and exitNo <= 266:
                            exitNo = 256
                        if exitNo >= 4297 and exitNo <= 4501:
                            exitNo=4297
                        if exitNo in self.exitCodeDic:
                            self.sendToPannel('backInfo::'+exitCode+'||'+self.exitCodeDic[exitNo])
                        else:
                            LogRecord.instance().logger.debug('返回无法解析的错误：'+exitCode)
                            self.sendToPannel('backInfo::'+exitCode+'||'+'连接代理失败，请联系管理员检查代理服务器状态或交付平台配置！')
                    except Exception,exp:
                        LogRecord.instance().logger.exception('返回错误码异常！')

#                     if exitCode == '2':
#                         print self.exitCodeDic[int(exitCode)]
#                         pass
#                     else:
#                         try:
#                             exitNo=int(exitCode)
#                             if exitNo >= 256 and exitNo <= 266:
#                                 exitNo = 256
#                             if exitNo >= 4297 and exitNo <= 4501:
#                                 exitNo=4297
#                             if exitNo in self.exitCodeDic:
#                                 print self.exitCodeDic[exitNo]
#                                 self.eventToPannel('notify::'+self.exitCodeDic[exitNo])
# #                                 notifyWidget=NotifyWedget()
# #                                 notifyWidget.showMessage(self.exitCodeDic[exitNo])
#                             else:
#                                 print '返回无法解析的错误：'+exitCode
#                                 LogRecord.instance().logger.debug('返回无法解析的错误：'+exitCode)
#                         except Exception,exp:
#                             print exp
#                             LogRecord.instance().logger.exception('返回错误码异常！')
#                         pass
                except Exception,exp:
                    LogRecord.instance().logger.exception('退出码异常！')

            #rdp连接异常退出

            elif reason.startswith('[callback::3'):
                #返回应用列表
                activities=reason[13:-1]
                # print activities.decode('GBK')
                self.sendToPannel('activites::'+activities)

            elif reason.startswith('[callback::100]'):
                #打开应用失败
                self.sendToPannel('appFailed::')

            elif reason.startswith('[HWND::'):
                #用于挂载工具栏
                window=reason[7:-1]
                self.sendToPannel('hwnd::'+window)
#                 AppTool(parentWnd=window)            

            elif reason.startswith('[rdp_event:1]'):
                #移动鼠标到窗口顶端，显示工具栏
                self.sendToPannel('toolDown::')



if __name__ == '__main__':
#     app = QtGui.QApplication(sys.argv)
    user=AppUser(r'www10.com\wang')
    user.setPassword('123456')
    user.setAgentIP('192.168.102.37')
    user.setAgentPort('3389')
    user.setRdpState('disconnected')
    user.setLoginState('ready')   
    appObj=AppObject('calculator','100')
    appObj.setAppPosition(0)
    appObj.setAppCommand('[startApp::C:\\Windows\\system32\\calc.exe]')
    appObj.setAppEnable(True)
    user.updateAppDictionary(appObj)
    application=AppApplication(user)
    application.appRDP.setFullScreen(False)
    application.startApp(0)
#     sys.exit(app.exec_()) 
   