package ru.kirillius.pf.sdn;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * Maintains a rolling in-memory buffer of recent log messages for diagnostics exposure.
 */
public class InMemoryLogHandler extends Handler {
    private final static Queue<String> queue = new ConcurrentLinkedQueue<>();

    private final static DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.US);

    /**
     * Formats a log record into a single-line message.
     */
    private String format(LogRecord logRecord) {
        return "[" + dateFormat.format(new Date(logRecord.getMillis())) + "][" + logRecord.getLevel().getName() + "] " + logRecord.getMessage().trim();
    }

    /**
     * Returns a read-only view of the buffered log messages.
     */
    public static Collection<String> getMessages() {
        return Collections.unmodifiableCollection(queue);
    }

    public static void clear() {
        queue.clear();
    }

    /**
     * Stores the formatted message in the buffer, trimming old entries when full.
     */
    @Override
    public void publish(LogRecord logRecord) {
        if (queue.size() >= 1000) {
            queue.poll();
        }
        queue.add(format(logRecord));
    }

    /**
     * No-op flush implementation.
     */
    @Override
    public void flush() {

    }

    /**
     * No-op close implementation.
     */
    @Override
    public void close() {

    }
}
