package weaver.interfaces.htsc.filter;

import com.htsc.trace.Tracer;
import com.htsc.trace.TracerFactory;
import com.htsc.trace.servlet.TraceServletFilter;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import java.io.IOException;

@Slf4j
public class HtscTraceFilter implements Filter {

    private Filter delegate = null;
    private volatile Tracer tracer = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("HtscTraceFilter init");
        System.out.println("HtscTraceFilter init");
        this.tracer = TracerFactory.getTraceInstance();
        if (this.tracer == null) {
            log.warn("tracer is not initialized");
            System.err.println("tracer is not initialized");
        } else {
            this.delegate = TraceServletFilter.create(this.tracer);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        if (this.tracer == null) {
            synchronized (HtscTraceFilter.class) {
                if (this.tracer == null) {
                    log.warn("initialize tracer");
                    this.tracer = TracerFactory.getTraceInstance();
                    log.info("get tracer [{}]", this.tracer);
                    this.delegate = TraceServletFilter.create(this.tracer);
                }
            }
        }
        delegate.doFilter(request, response, chain);
    }

    @Override public void destroy() {
    }

}
