# -*- coding: utf-8 -*-
import json
import logging
import os
import sys
import time

import datetime
import numpy as np
import struct
import binascii

from ssat_sdk.utils.string_util import pathToWindowsPath

from ssat_sdk.sat_environment import getSATTmpDIR, writeIsSendKeyTakePicture

from ssat_sdk.sat_environment import getRunnerTcpPort
import socket
_IsLoggerCreated = None

# log tcp 客户端;


class logClient:
    def __init__(self):
        self.sock = None
        self.port = getRunnerTcpPort()
        self.constate = False

    def __del__(self):
        self.disconnect()

    # 连接服务器;
    def connect(self):
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.port = getRunnerTcpPort() # 再读取一次端口号;
            self.sock.connect(('127.0.0.1', self.port)) #没有返回值;
            self.constate = True
        except Exception, e:
            print "LoggingUtil:client=> socket connect error:", e, self.port
            self.constate = False
        
        return self.constate

    # 发送消息;
    def sendmsg(self, msg, type = 'printLog'):
        if self.constate is False:
            if self.connect() is False:
                return

        msg_json = ""
        msg_dict = {'ReportType': type, 'prinMsg': msg}
        try:
            msg_json = json.dumps(msg_dict)
        except Exception:
            print "LoggingUtil:client=> to json error:", msg
            return

        try:
            self.sock.settimeout(1)
            self.sock.sendall(msg_json)
            self.sock.settimeout(None)
        except Exception, e:
            print "LoggingUtil:client=>无Runner接收结果。Error:", e, 'runner_sender_port:', self.port
            self.disconnect()
            self.connect()

    # 断开连接;
    def disconnect(self):
        if self.sock is None:
            return
        try:
            self.sock.shutdown(2)
            self.sock.close()
        except Exception, e:
            print "LoggingUtil:client=> socket disconnect error:", e


# 定义:
DataHeader = np.dtype({'names': ['protocol', 'len', 'cmd'], 'formats': ['u1', 'u4', 'u1']}, align=False)
# 通知SATService正常关机、重启;
NoticeResp = np.dtype({'names': ['TimeStamp', 'NoticeType'], 'formats': ['u8', 'u4']}, align=False)
class noticeClient:

    def __init__(self):
        '''通信sock'''
        self.sock = None
        '''通信端口号'''
        self.port = getRunnerTcpPort()
        '''通信状态'''
        self.constate = False

    def __def__(self):
        self.disconnect()

    '''连接服务器'''

    def connect(self):
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect(('127.0.0.1', self.port))  # 没有返回值;
            self.sock.sendall("2222")
            self.constate = True
        except Exception, e:
            print "noticeClient=> socket connect error:", e, self.port
            self.constate = False

        return self.constate
    
    # 发送通知,不接收返回;
    def sendnotice(self, type):
        '''是否连接'''
        if self.constate is False:
            if self.connect() is False:
                print u'连接服务器失败'
                return False

        '''拼装要发送的数据包'''
        notice = np.array([(time.time(), type)], dtype=NoticeResp)

        '''发送请求数据'''
        try:
            self.sock.settimeout(5)
            phead = np.array([(0xAA, notice.itemsize + np.array([(0xAA, 0, 0x01)], dtype=DataHeader).itemsize, 0x06)], dtype=DataHeader)
            '''一次性发送完整包'''
            self.sock.sendall(bytearray(phead.tobytes() + notice.tobytes()))
            self.sock.settimeout(None)
        except Exception, e:
            print "noticeClient=> send Error:", e
            self.disconnect()
            self.connect()
            return False
        
        print u'成功发送'
        return True
       

    '''断开连接'''

    def disconnect(self):
        try:
            self.sock.shutdown(2)
            self.sock.close()
        except Exception, e:
            print "noticeClient=> socket disconnect error:", e

# 单例模块;
logClient_singleton = logClient()
noticeClient_singleton = noticeClient()

def sendKey(keyname, keyExit):
    if keyExit:
        msg = currentTime() + '执行sendKey:' + keyname
    else:
        msg = currentTime() + 'sendKey:' + keyname + '不存在'
    print msg


def takePicpure(result, picpath):
    # msg = {'ReportType': "takePicpure", 'data': {'result': result, 'picpath': picpath}}
    msg = currentTime() + 'takePicture:' + '截图结果:' + \
        str(result) + '截图路径:' + picpath
    print msg


def printLog(tag='', logmsg=''):
    # msg = {'ReportType': "printLog", 'data': {'logmsg': logmsg}}
    if logmsg == '':
        msg = currentTime() + 'printLog:%s' % str(tag)
        tcpMsg = str(tag)
    else:
        msg = currentTime() + 'printLog:%s:%s' % (str(tag), str(logmsg))
        tcpMsg = str(tag) + str(logmsg)
    print msg
    # logClient_singleton.sendmsg(tcpMsg)

def NotifyShutdown():
    # 参数0表示正常关机;
    noticeClient_singleton.sendnotice(0)

def NotifyReboot():
    # 参数1表示正常重启;
    noticeClient_singleton.sendnotice(1)

def caseResult(caseresult):
    # msg = {'ReportType': "printLog", 'data': {'logmsg': logmsg}}
    # 改用TCP方式发送结果给Runner端
    msg = currentTime() + u'TcpClient发送的信息caseResult:' + caseresult
    print msg


def currentTime():
    return time.strftime('%Y-%m-%d   %H:%M:%S  ', time.localtime(time.time()))


# log标签
createdlogTab = 'default'
# 记录当前保存的log的文件夹路径
caseRunLogDirPath = os.path.join(getSATTmpDIR(), 'case_run_no_created')
# 记录关闭之前保存的log的文件夹路径
debugCaseRunLogDirPath = os.path.join(getSATTmpDIR(), 'case_run_no_created')
# 自定义DebugLogger对象
debugLogger = None
Tag_pyFileName = os.path.split(__file__)[-1]


class DebugLogger():
    def info(self, pyFileName, className, funName, msg):
        # 打印Log信息
        logtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        logMsg = "%s  %s  %s.%s  INFO  %s \n" % (logtime, pyFileName, className, funName, msg)
        print "调试信息=>",logMsg
        # 往文件里面写log信息
        mkCasedir(caseRunLogDirPath)
        filePath = os.path.join(caseRunLogDirPath, 'case_run.log')
        fp = open(filePath, 'a')
        fp.write(logMsg)
        fp.close()
        # writeDeviceMsgLine(fp,logMsg)


def getDebugLogger():
    global debugLogger
    if not debugLogger:
        debugLogger = DebugLogger()
    return debugLogger


def closeFileHandler(logTab='default'):
    global createdlogTab, caseRunLogDirPath
    # 如果传进来的创建log文件来源和关闭来源相等,则关闭该文件流
    print 'createdlogTab:', createdlogTab, 'logTab:', logTab
    # 关闭log打印流时候,把按键打印截图开关 关闭
    closeSendKeyTakePicture()
    if logTab != 'default' and logTab == createdlogTab:
        debugLogPath = os.path.join(caseRunLogDirPath, 'case_run.log')
        getDebugLogger().info('Loggger.py', 'NoClass', 'closeFileHandler',
                              u'关闭Tab:%s的case_run.log文件保存路径:%s' % (logTab, pathToWindowsPath(debugLogPath)))
        caseRunLogDirPath = os.path.join(getSATTmpDIR(), 'case_run_no_created')
        createdlogTab = 'default'


def createFileHandler(logTab='default'):
    global createdlogTab, caseRunLogDirPath, debugCaseRunLogDirPath
    # closeFileHandler()
    print 'createFileHandler createdlogTab:', createdlogTab
    # 创建log文件夹时,把按键打印截图开关打开
    startSendKeyTakePicture()
    if createdlogTab == 'default':
        print '创建文件'
        caseRunLogDir = 'case_run_' + \
            '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
        caseRunLogDirPath = os.path.join(getSATTmpDIR(), caseRunLogDir)
        # 在调试的时候,记录调试信息路径
        debugCaseRunLogDirPath = caseRunLogDirPath
        mkCasedir(caseRunLogDirPath)
        debugLogPath = os.path.join(caseRunLogDirPath, 'case_run.log')
        getDebugLogger().info('Loggger.py', 'NoClass', 'closeFileHandler',
                              u'创建Tab:%s的case_run.log文件保存路径:%s' % (logTab, pathToWindowsPath(debugLogPath)))
        # 用于编辑该log文件创建的来源
        createdlogTab = logTab


def startSendKeyTakePicture():
    writeIsSendKeyTakePicture("True")


def closeSendKeyTakePicture():
    writeIsSendKeyTakePicture("False")


def getCaseRunLogDirPath():
    global caseRunLogDirPath
    mkCasedir(caseRunLogDirPath)
    return caseRunLogDirPath


def getDebugCaseRunLogDirPath():
    global debugCaseRunLogDirPath
    return debugCaseRunLogDirPath


def mkCasedir(dir):
    if (not os.path.exists(dir)):
        os.mkdir(dir)


if __name__ == "__main__":
    # getDebugLogger().info(Tag_pyFileName, 'NoClass', '__main__', u"当前界面即为目标界面000")
    # createFileHandler('scrpt')
    # getDebugLogger().info(Tag_pyFileName, 'NoClass', '__main__', u"当前界面即为目标界面")
    # createFileHandler('toDestUI')
    # getDebugLogger().info(Tag_pyFileName, 'NoClass', '__main__', u"当前界面即为目标界面222")
    # getDebugLogger().info(Tag_pyFileName, 'NoClass', '__main__', u"当前界面即为目标界面333")
    # getDebugLogger().info(Tag_pyFileName, 'NoClass', '__main__', u"当前界面即为目标界面444")
    # closeFileHandler('toDestUI')
    # getDebugLogger().info(Tag_pyFileName, 'NoClass', '__main__', u"当前界面即为目标界面555")
    # closeFileHandler('scrpt')
    # createFileHandler('toDestUI')
    # getDebugLogger().info(Tag_pyFileName, 'NoClass', '__main__', u"当前界面即为目标界面666")
    # time.sleep(15)
    # getDebugLogger().info(Tag_pyFileName, 'NoClass', '__main__', u"当前界面即为目标界面222")
    # deleteDebugLofFile()
    # getDebugLogger().info('')
    # deleteDebugLofFile()
    # print os.times()
    # now_time = datetime.datetime.now()
    # print now_time
    # print '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
    # createFileHandler('script')
    # getDebugLogger().info(u"当前界面即为目标界面")
    # getDebugLogger().info(u"当前界面即为目标界面22")
    # getDebugLogger().info(u"当前界面即为目标界面33")
    # print 'getCaseRunLogDirPath:', getCaseRunLogDirPath()
    # closeFileHandler('script')
    # # time.sleep(5)
    # createFileHandler('toDestUI')
    # getDebugLogger().info(u"当前界面即为目标界面")
    # print 'getCaseRunLogDirPath:', getCaseRunLogDirPath()
    # closeFileHandler('toDestUI')
    NotifyReboot()