import threading
from datetime import datetime


class MaxTopicLength:
    def __init__(self):
        self.max_mqtt_topic_length = 1
        self.mqtt_log_reformat_event = threading.Event()

    def process_topic(self, topic):
        if len(topic) > self.max_mqtt_topic_length:
            self.max_mqtt_topic_length = len(topic)
            print(f'new long topic length: {self.max_mqtt_topic_length}')
            self.mqtt_log_reformat_event.set()
        return self.max_mqtt_topic_length

    def get_and_clear(self):
        if self.mqtt_log_reformat_event.is_set():
            self.mqtt_log_reformat_event.clear()
            return True
        return False


def format_log_msg(topic: str, max_mqtt_topic_length: int, message: str, timestamp: datetime = None):
    now = timestamp or datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # padding = max_mqtt_topic_length - len(topic) + 1
    return f'[{now} @ {topic:{max_mqtt_topic_length}}] {message}'


def parse_log_msg(entry: str):
    at_index = entry.index('@')
    closing_bracket_index = entry.index(']')
    return entry[1:at_index].strip(), entry[at_index + 1:closing_bracket_index].strip(), entry[closing_bracket_index+2:]