package cn.axzo.msg.center.notices.client.util;

import ch.qos.logback.core.Layout;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import com.xxl.job.core.log.XxlJobFileAppender;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yanglin
 */
public class XxlAppender<E> extends UnsynchronizedAppenderBase<E> {

    private final ReentrantLock lock = new ReentrantLock(false);
    private Encoder<E> encoder;

    @SuppressWarnings("unused")
    public void setLayout(Layout<E> layout) {
        LayoutWrappingEncoder<E> lwe = new LayoutWrappingEncoder<>();
        lwe.setLayout(layout);
        lwe.setContext(context);
        this.encoder = lwe;
    }

    @Override
    protected void append(E event) {
        String logFileName = XxlJobFileAppender.contextHolder.get();
        if (logFileName == null) return;
        if (encoder == null) return;
        byte[] bytes = encoder.encode(event);
        String message = new String(bytes);
        lock.lock();
        try {
            XxlJobFileAppender.appendLog(logFileName, message);
        } catch (Exception e) {
            //noinspection CallToPrintStackTrace
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }

}