# -*- coding:utf-8 -*-
import os
import sys
import time
from ctypes.wintypes import HWND, LPCSTR, UINT
from ctypes import *
import chardet
# 加载dll;
logdll = CDLL(r'E:\bin\LogModule\logmodule.DLL')

'''
Python 2.x中，默认编码为ascii;
如果在文件中指定编码为utf-8,要转在gbk是无法直接转的；需要先转换成unicode，再转成gbk；

Python 3.x，默认编码为unicode；
如果在文件中指定编码为uft-8，可以直接转gbk；
'''


if __name__ == '__main__':
    # time.sleep(20)
    # 启动服务;
    if logdll.StartServer(5566):
        print "启动服务成功"
    else:
        print "启动服务失败"

    # 启用写日志;
    logdll.EnableWriteLog(True)

    '''
    # 设置日志路径一;
    #
    # 错误方式：logdll.SetCaselogPath(r"E:\bin\城aa\我们aa.txt")  C++默认编码为GBK, Python为utf-8，无法直接传递;
    #
    '''

    '''
    # 设置日志路径二;
    #
    # 正确方式：若python字符编码为unicode，直接将unicode转码为gbk
    #
    '''
    if 0:
        path = u"E:\\bin\\测试日志\\测试日志.txt"
        print type(path)
        logdll.SetCaselogPath(path.encode("gbk"))

        '''
        # 获取日志路径;
        '''
        logdll.GetCaselogPath.restype = POINTER(c_byte)
        path = logdll.GetCaselogPath()
        dir = string_at(path, -1).decode("gbk")
        print dir

    '''
    # 设置日志路径三;
    #
    # 正确方式：若python字符编码为utf-8，先将python字符utf-8转码为unicode，再将unicode转码为gbk
    #
    '''
    if 0:
        # 先解码utf-8为unicod,再转码为gbk;
        path = "E:\\bin\\城aa\\我们aa.txt"
        print type(path)
        print chardet.detect(path)
        logdll.SetCaselogPath(path.decode("utf-8").encode('gbk'))

    '''
    C接口: const int& len参数传递过程中会报错;改为int len不会报错;
    '''
    if 0:
        path = "E:\\bin\\城aa\\我们aa.txt"
        print chardet.detect(path)
        logdll.SetCaselogPath2(path.decode("utf-8").encode('gbk'), path.__len__())

        '''
        # 获取日志路径;
        '''
        logdll.GetCaselogPath.restype = POINTER(c_byte)
        path = logdll.GetCaselogPath()
        dir = string_at(path, -1).decode("utf-8")
        print dir

    index = 0
    # 获取最后的接收时间戳;
    logdll.GetReceivePrintTime.restype = c_int64
    while True:
        logdll.EnableWriteLog(True)
        time.sleep(0.1)
        path = r"E:\bin\测试日志\测试日志%d.txt" % index
        print "日志路径", path
        logdll.SetCaselogPath(path.decode("utf-8").encode('gbk'))
        dt = logdll.GetReceivePrintTime()
        print "时间：", dt, time.time(), time.time() - dt
        time.sleep(60)
        logdll.EnableWriteLog(False)
        time.sleep(0.1)
        index = index+1

    # 停止服务;
    logdll.StopServer()
