package kr.gmtc.gw.standstatus.logger;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.spi.FilterReply;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CaptureAppender extends AppenderBase<ILoggingEvent> {

    /**
     * Guard flag to prevent recursive calling of the appender.
     */
    boolean guard;


    /**
     * Flag indicates that the appender is collecting the contents and storing them away
     */

    private boolean collect;

    /**
     * STorage location for captured HTTP output.
     */

    private List<String> capturedOutput = new ArrayList<>();

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected synchronized void append(ILoggingEvent evt)
    {

        if (guard) {
            return;
        }

        try {
            guard = true;

            if (!this.started) {
                return;
            }

            if (getFilterChainDecision(evt) == FilterReply.DENY) {
                return;
            }

            capturedOutput.add(evt.getMessage());

        } finally {
            guard = false;
        }
    }

    public void startCollecting() {
        this.collect = true;
        this.capturedOutput.clear();
    }

    public List<String> stopCollecting() {
        this.collect = false;

        List<String> immutaList = new ArrayList<>();
        immutaList.addAll(this.capturedOutput);
        immutaList = Collections.unmodifiableList(immutaList);

        return immutaList;
    }
}