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


class logClient:
    def __init__(self):
        self.port = 5566
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.constate = False

    def __del__(self):
        self.disconnect()

    # 连接服务器;
    def connect(self):
        try:
            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):
        if self.constate is False:
            if self.connect() is False:
                return

        msg_json = ""
        msg_dict = {'ReportType': 'printLog', '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):
        try:
            self.sock.shutdown(2)
            self.sock.close()
        except Exception, e:
            print "LoggingUtil:client=> socket disconnect error:", e


# 单例模块;
logClient_singleton = logClient()

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


def print_log(tag='', logmsg=''):
    if logmsg == '':
        msg = current_time() + 'printLog: %s' % str(tag)
        tcp_msg = str(tag)
    else:
        msg = current_time() + 'printLog: %s:%s' % (str(tag), str(logmsg))
        tcp_msg = str(tag) + str(logmsg)
    print msg
    logClient_singleton.sendmsg(tcp_msg)


if __name__ == '__main__':
    # print_log("printLog", "测试中……")
    # print_log(unicode("this step is: Index : " + "1" + "    Name: " + str("1")+ "    Desc: " + str("1") + "    result: " + "Detail"))
    # print_log("this step is: Index : " + "我" + "    Name: " + str("1")+ "    Desc: " + str("1") + "    result: " + "Detail")

    # test_basic_general("1.jpg")
    # test_basic_acurate("1.jpg")
    # test_getStrWithImgProcess()
    # print_log("printLog", "Test_Fail:Timing%s，%s截图，红场的比例与标准比例差异过大！&#10;")

    while True:
        time.sleep(5)
        print_log("printLog", "测试中……")
        # print_log("printLog", "Test_Fail:Timing%s，%s截图，红场的比例与标准比例差异过大！&#10;")
        # time.sleep(2)
        #         # print_log("printLog", u"测试中……")