# coding:utf-8
from ctypes import *
import threading
import time
from logger.logrecord import LogRecord


CALLBACK = CFUNCTYPE(c_int, c_char_p)


@CALLBACK
def c_callback(msg):
    if XFRDP.callback is not None:
        XFRDP.callback(msg)
    else:
        LogRecord.instance().logger.info('callback is None!!!!!!!!')
    return 0


class XFRDP():
    """云应用python接口"""

    callback = None
    context = 0

    def __init__(self, libpath):
        self.clib = CDLL(libpath)
        self.context = 0
        self.clib.xf_rdp_create.restype = c_long
        self.clib.xf_rdp_connect.argtypes = [c_long]
        self.clib.xf_rdp_disconnect.argtypes = [c_long]
        self.clib.xf_rdp_wait_end.argtypes = [c_long]
        self.clib.xf_rdp_hide_window.argtypes = [c_long]
        self.clib.xf_rdp_show_window.argtypes = [c_long]
        self.clib.xf_rdp_register.argtypes = [c_long, c_void_p]
        self.clib.xf_rdp_send_command.argtypes = [c_long, c_char_p]
        self.clib.xf_rdp_get_error_info.restype = c_char_p

    def create_connection(self, callback, args):
        '''
        建立rdp连接
        '''
        if XFRDP.context != 0:
            LogRecord.instance().logger.info('Already connected')
            self.disconnect()
            time.sleep(1)
        args = args.split()
        n = len(args) + 1
        array_type = c_char_p * n
        cargs = array_type()

        cargs[0] = 'xf_rdp'
        for i, v in enumerate(args):
            cargs[i + 1] = v
        # 创建context
        XFRDP.context = self.clib.xf_rdp_create(n, cargs)
        if XFRDP.context == 0:
            return False

        XFRDP.callback = callback
        # 注册回调
        # _callback = CALLBACK(XFRDP.c_callback)
        self.clib.xf_rdp_register(XFRDP.context, c_callback)

        # 建立rdp连接
        self.clib.xf_rdp_connect(XFRDP.context)

        # 监听连接断开事件
        self.thread = threading.Thread(target=self._wait_rdp_end)
        self.thread.setDaemon(True)
        self.thread.start()
        return True

    def disconnect(self):
        '''
        端口rdp连接
        '''
        if XFRDP.context == 0:
            return False
        self.clib.xf_rdp_disconnect(XFRDP.context)
        XFRDP.context = 0
        return True

    def send_command(self, s):
        '''
        向cloud通道发送消息
        '''
        if XFRDP.context == 0:
            return False
        print(s)
        self.clib.xf_rdp_send_command(XFRDP.context, s)
        return True

    def hide_window(self):
        if XFRDP.context == 0:
            return False
        self.clib.xf_rdp_hide_window(XFRDP.context)
        return True

    def show_window(self):
        if XFRDP.context == 0:
            return False
        self.clib.xf_rdp_show_window(XFRDP.context)
        return True

    def get_error_info(self, code):
        s = self.clib.xf_rdp_get_error_info(code)
        return s

    def _wait_rdp_end(self):
        if XFRDP.context == 0:
            return
        ret = self.clib.xf_rdp_wait_end(XFRDP.context)
        LogRecord.instance().logger.info('_wait_rdp_end running--------------------')
        XFRDP.context = 0
        s = ''
        if 0 == ret:
            s = '[callback::10]'
        else:
            err_info = self.get_error_info(ret)
            s = '[callback::30||' + str(ret) + '&&' + err_info + ']'
        XFRDP.callback(s)


def _cloud_callback(s):
    LogRecord.instance().logger.info('_cloud_callback: ' + s)
    return 0

if __name__ == '__main__':
    import time
    import os
    libpath = os.path.dirname(os.path.abspath(__file__))
    libpath = os.path.join(libpath, 'client', 'X11', 'libxfreerdp-client.so')
    rdp = XFRDP(libpath)
    args = '/v:192.168.1.76 /u:zsy /p:Pass1234 /f'
    rdp.create_connection(_cloud_callback, args)
    time.sleep(10)
    rdp.send_command('[startApp::C:\\Windows\\system32\\calc.exe]')
    time.sleep(5)
    rdp.hide_window()
    time.sleep(5)
    rdp.show_window()
    time.sleep(5)
    rdp.disconnect()
    time.sleep(5)
