//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.yihu.hos.common.format;

import com.yihu.hos.core.constants.CoreConstant;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.core.datatype.StringUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.PatternConverter;
import org.apache.log4j.helpers.PatternParser;
import org.apache.log4j.spi.LoggingEvent;

import java.util.HashMap;
import java.util.Map;

public class PatternLayout extends Layout {
    public static final String DEFAULT_CONVERSION_PATTERN = "%m%n";
    public static final String TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n";
    protected final int BUF_SIZE;
    protected final int MAX_CAPACITY;
    private StringBuffer sbuf;
    private String pattern;
    private PatternConverter head;

    public PatternLayout() {
        this("%m%n");
    }

    public PatternLayout(String pattern) {
        this.BUF_SIZE = 256;
        this.MAX_CAPACITY = 1024;
        this.sbuf = new StringBuffer(256);
        this.pattern = pattern;
        this.head = this.createPatternParser(pattern == null?"%m%n":pattern).parse();
    }

    public void setConversionPattern(String conversionPattern) {
        this.pattern = conversionPattern;
        this.head = this.createPatternParser(conversionPattern).parse();
    }

    public String getConversionPattern() {
        return this.pattern;
    }

    public void activateOptions() {
    }

    public boolean ignoresThrowable() {
        return true;
    }

    protected PatternParser createPatternParser(String pattern) {
        return new PatternParser(pattern);
    }

    public String format(LoggingEvent event) {
        if (StringUtil.isEmpty(event.getMDC("camel.messageId"))) {
            return CoreConstant.EMPTY;
        }
        String message = event.getMessage().toString();
        String body = message.substring(message.indexOf("Body:") + 5);
        Map<String, String> map = new HashMap<>();
        map.put("exchangeId", StringUtil.toString(event.getMDC("camel.exchangeId")));
        map.put("correlationId", StringUtil.toString(event.getMDC("camel.correlationId")));
        map.put("transactionKey", StringUtil.toString(event.getMDC("camel.transactionKey")));
        map.put("routeId", StringUtil.toString(event.getMDC("camel.routeId")));
        map.put("breadcrumbId",StringUtil.toString(event.getMDC("camel.breadcrumbId")));
        map.put("camelContextId", StringUtil.toString(event.getMDC("camel.contextId")));
        map.put("body", body);
        map.put("fireTime", DateUtil.getCurrentString());
        return JSONObject.fromObject(map).toString();
    }
}
