# -*- coding: utf-8 -*-
import re
import sys
import logging

from aegis_checker.common.print_log import *
from aegis_checker.common.aegis_client_log_parser import LogObserver, LOG_INFO
from aegis_checker.info.check_result import *


class LoginObserver(LogObserver):
    def __init__(self):
        self.__login_events = []
        self.__login_start_event = None
        self.__login_end_event = None
        self.__login_fail_count = 0

    def on_log(self, log_date, log_time, log_type, content, line, line_num, log_file_path):
        """
        2020-04-13 02:35:50 [Info] SendMessage T_MSG_LOGIN
        2020-04-13 02:35:50 [Info] GetMessage : T_MSG_LOGIN_RSP
        2020-04-13 02:35:50 [Info] GetMessage : T_MSG_MACHINE_INFO
        2020-04-13 02:35:51 [Info] GetMessage : T_MSG_PUSH_CLIENT_CONF
        :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:
        """
        if log_type == LOG_INFO and content.startswith("SendMessage T_MSG_LOGIN"):
            logging.info("aegis client try to login at %s %s", log_date, log_time)
            if self.__login_start_event:
                self.__login_fail_count += 1
                logging.warning(
                    "offline may be caused by login fail, no response after send login message to aegis server at %s %s" % (
                        self.__login_start_event["date"], self.__login_start_event["time"]))


            self.__login_start_event = self.wrapper_event(log_date, log_time, content)
            self.__login_end_event = None

        if log_type == LOG_INFO and content.startswith("GetMessage : T_MSG_LOGIN_RSP"):
            self.__login_end_event = self.wrapper_event(log_date, log_time, content)
            log_info("aegis client login success at %s %s" % (log_date, log_time))
            self.__login_start_event = None

    def on_end(self, success):
        if (self.__login_start_event is None) and (self.__login_end_event is None):
            log_warning("there is no login event")
        elif self.__login_end_event is None:
            output = "offline may be caused by login fail, no response after send login message to aegis server at %s %s" % (
                self.__login_start_event["date"], self.__login_start_event["time"])
            log_warning(output)
            set_root_cause(ROOT_CAUSE_AEGIS_LOGIN_FAIL, output)

        if self.__login_fail_count > 0:
            set_root_cause(ROOT_CAUSE_AEGIS_LOGIN_FAIL, "offline may be caused by login fail, no response after send login message to aegis server %d times" % self.__login_fail_count)


if __name__ == '__main__':
    logging.basicConfig(format='%(asctime)s [%(filename)s][%(levelname)s] %(message)s', level=logging.DEBUG)
    login_observer = LoginObserver()
    log_file_path = sys.argv[1]
    with open(log_file_path) as f:
        regular = r"^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) \[(\w+)\] (.+)"
        reg = re.compile(regular, re.I)
        line_num = 0
        for line in f:
            match_obj = reg.match(line)
            if match_obj:
                log_date, log_time, log_type, content = match_obj.groups()
                login_observer.on_log(log_date, log_time, log_type, content, line, line_num, log_file_path)
            line_num += 1

        login_observer.on_end(True)
