package org.apache.logging.log4j.core.pattern;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;

@Plugin(
   name = "MdcPatternConverter",
   category = "Converter"
)
@ConverterKeys({"X", "mdc", "MDC"})
public final class MdcPatternConverter extends LogEventPatternConverter {
   private final String key;

   private MdcPatternConverter(String[] options) {
      super(options != null && options.length > 0 ? "MDC{" + options[0] + '}' : "MDC", "mdc");
      this.key = options != null && options.length > 0 ? options[0] : null;
   }

   public static MdcPatternConverter newInstance(String[] options) {
      return new MdcPatternConverter(options);
   }

   public void format(LogEvent event, StringBuilder toAppendTo) {
      Map<String, String> contextMap = event.getContextMap();
      if (this.key == null) {
         if (contextMap == null || contextMap.isEmpty()) {
            toAppendTo.append("{}");
            return;
         }

         StringBuilder sb = new StringBuilder("{");
         Set<String> keys = new TreeSet(contextMap.keySet());

         String key;
         for(Iterator i$ = keys.iterator(); i$.hasNext(); sb.append(key).append('=').append((String)contextMap.get(key))) {
            key = (String)i$.next();
            if (sb.length() > 1) {
               sb.append(", ");
            }
         }

         sb.append('}');
         toAppendTo.append(sb);
      } else if (contextMap != null) {
         Object val = contextMap.get(this.key);
         if (val != null) {
            toAppendTo.append(val);
         }
      }

   }
}
