# -*- coding: utf-8 -*-
# this script is use to extract waning, error and critical log
import os
import sys


from aegis_checker.common.common_path import get_log_dir
from aegis_checker.common.aegis_client_log_parser import LogObserver, LOG_WARN, LOG_ERROR, LOG_CRITICAL


class ErrorLogObserver(LogObserver):
    def __init__(self):
        error_log_path = os.path.join(get_log_dir(), "aegis_client_error.log")
        self.__error_log = open(error_log_path, "w")

    def __del__(self):
        self.__close_error_log()

    def __close_error_log(self):
        if self.__error_log:
            self.__error_log.close()
            self.__error_log = None

    def on_log(self, log_date, log_time, log_type, content, line, line_num, log_file_path):
        """
        :param log_date:
        :param log_time:
        :param log_type: Debug, Info, Warn, Error, Critical
        :param content: log without timestamp and log type : "SendMessage T_MSG_LOGIN"
        :param line: origin log with timestamp and log type
        :return:
        """
        error_log_types = [
            LOG_WARN,
            LOG_ERROR,
            LOG_CRITICAL
        ]

        if log_type in error_log_types:
            self.__error_log.write(line)

    def on_end(self, success):
        self.__close_error_log()
