package com.virjar.echo.adr.component;

import com.virjar.echo.nat.log.EchoLogger;
import com.virjar.echo.nat.log.ILogger;

import java.util.concurrent.atomic.AtomicLong;

public class LogServices {
    private static final int bufferSize = 30;
    private static String[] buffer;
    private static AtomicLong index = new AtomicLong(0);

    private static class EchoPrintLogger implements ILogger {
        private ILogger delegate;

        public EchoPrintLogger(ILogger delegate) {
            this.delegate = delegate;
        }

        @Override
        public void info(String msg) {
            addLog(msg);
            delegate.info(msg);
        }

        @Override
        public void info(String msg, Throwable throwable) {
            addLog(msg);
            delegate.info(msg, throwable);
        }

        @Override
        public void warn(String msg) {
            addLog(msg);
            delegate.warn(msg);
        }

        @Override
        public void warn(String msg, Throwable throwable) {
            addLog(msg);
            delegate.warn(msg, throwable);
        }

        @Override
        public void error(String msg) {
            addLog(msg);
            delegate.error(msg);
        }

        @Override
        public void error(String msg, Throwable throwable) {
            addLog(msg);
            delegate.error(msg, throwable);
        }
    }

    public static void init() {
        buffer = new String[bufferSize];
        ILogger logger = EchoLogger.getLogger();
        EchoLogger.setLogger(new EchoPrintLogger(logger));
    }

    public static void addLog(String message) {
        long insertIndex = index.getAndIncrement();
        buffer[(int) (insertIndex % buffer.length)] = message;
    }

    public static StringBuffer logSnapshot() {
        StringBuffer stringBuffer = new StringBuffer(20 * 32);
        int readStartIndex = (int) (index.get() % buffer.length) + buffer.length - 1;
        for (int i = 0; i < buffer.length; i++) {
            int readIndex = (readStartIndex - i) % buffer.length;
            String log = buffer[readIndex];
            if (log == null) {
                break;
            }
            stringBuffer.append(log).append("\n");
        }
        return stringBuffer;
    }

}
