# -*- coding:utf-8 -*-

import wx
import logging
import os
import time
from pathlib import Path
from datetime import datetime


class TextHandler(logging.Handler):
    def __init__(self) -> None:
        logging.Handler.__init__(self)
        self.ctrl = None

    def set_ctrl(self, ctrl):
        self.ctrl = ctrl

    def emit(self, record):
        if not self.ctrl == None:
            wx.CallAfter(self.ctrl.write, self.format(record) + "\n")


class LogUtils(object):
    log = None

    # 实现一个静态方法实例
    @staticmethod
    def sharedInstance(task_id):
        if LogUtils.log == None:
            LogUtils.log = LogUtils(task_id)
        return LogUtils.log

    def __init__(self, task_id) -> None:
        self.logger = logging.getLogger(task_id)
        self.level = logging.INFO
        self.fmt = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
        self.text_ctrl = None
        self.text_handler = TextHandler()

    def set_logger(self, task_id, log_path, log_name=''):
        '''log目录设置'''
        if not os.path.exists(log_path):
            os.makedirs(log_path)

        if log_name == '':
            log_name = '%s_%s.log' % (
                task_id, datetime.now().strftime("%Y%m%d_%H%M%S_%f"))

        logs_folder = Path(log_path)
        self.logs_path = logs_folder / log_name
        print(self.logs_path)

        # 文件句柄
        fh = logging.FileHandler(self.logs_path)
        # 设置格式
        fh.setFormatter(self.fmt)
        # 添加文件输出流
        self.logger.addHandler(fh)

        # 输出到控制台
        sh = logging.StreamHandler()
        # 设置格式
        sh.setFormatter(self.fmt)
        # 添加标准输出流
        self.logger.addHandler(sh)

        # 自定义log重定向
        self.logger.addHandler(self.text_handler)
        self.logger.setLevel(logging.INFO)
        self.logger.info(u'Logging start.\n')

    def info(self, s):
        self.logger.info(s)

    def set_ctrl_to_logging(self, text_ctrl):
        self.text_ctrl = text_ctrl
        if not self.text_handler == None:
            self.text_handler.set_ctrl(self.text_ctrl)

    def get_current_log_file(self):
        return self.logs_path
