/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache license, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the license for the specific language governing permissions and
 * limitations under the license.
 */
package org.apache.logging.log4j.core.pattern;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.util.Loader;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.MultiformatMessage;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.MultiFormatStringBuilderFormattable;
import org.apache.logging.log4j.util.PerformanceSensitive;
import org.apache.logging.log4j.util.StringBuilderFormattable;

/**
 * Returns the event's rendered message in a StringBuilder.
 */
@Plugin(name = "MessagePatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({ "m", "msg", "message" })
@PerformanceSensitive("allocation")
public class MessagePatternConverter extends LogEventPatternConverter {

    private static final String LOOKUPS = "lookups";
    private static final String NOLOOKUPS = "nolookups";

    private MessagePatternConverter() {
        super("Message", "message");
    }

    private static int loadLookups(final String[] options) {
        if (options != null) {
            for (int i = 0; i < options.length; i++) {
                final String option = options[i];
                if (LOOKUPS.equalsIgnoreCase(option)) {
                    return i;
                }
            }
        }
        return -1;
    }

    private static TextRenderer loadMessageRenderer(final String[] options) {
        if (options != null) {
            for (final String option : options) {
                switch (option.toUpperCase(Locale.ROOT)) {
                case "ANSI":
                    if (Loader.isJansiAvailable()) {
                        return new JAnsiTextRenderer(options, JAnsiTextRenderer.DefaultMessageStyleMap);
                    }
                    StatusLogger.getLogger()
                            .warn("You requested ANSI message rendering but JANSI is not on the classpath.");
                    return null;
                case "HTML":
                    return new HtmlTextRenderer(options);
                }
            }
        }
        return null;
    }

    /**
     * Obtains an instance of pattern converter.
     *
     * @param config
     *            The Configuration.
     * @param options
     *            options, may be null.
     * @return instance of pattern converter.
     */
    public static MessagePatternConverter newInstance(final Configuration config, final String[] options) {
        boolean lookups = loadLookups(options) >= 0;
        String[] formats = withoutLookupOptions(options);
        TextRenderer textRenderer = loadMessageRenderer(formats);
        MessagePatternConverter result = formats == null || formats.length == 0
                ? SimpleMessagePatternConverter.INSTANCE
                : new FormattedMessagePatternConverter(formats);
        if (lookups && config != null) {
            result = new LookupMessagePatternConverter(result, config);
        }
        if (textRenderer != null) {
            result = new RenderingPatternConverter(result, textRenderer);
        }
        return result;
    }

    private static String[] withoutLookupOptions(final String[] options) {
        if (options == null || options.length == 0) {
            return options;
        }
        List<String> results = new ArrayList<>(options.length);
        for (String option : options) {
            if (!LOOKUPS.equalsIgnoreCase(option) && !NOLOOKUPS.equalsIgnoreCase(option)) {
                results.add(option);
            }
        }
        return results.toArray(new String[0]);
    }

    @Override
    public void format(final LogEvent event, final StringBuilder toAppendTo) {
        throw new UnsupportedOperationException();
    }

    private static final class SimpleMessagePatternConverter extends MessagePatternConverter {
        private static final MessagePatternConverter INSTANCE = new SimpleMessagePatternConverter();

        /**
         * {@inheritDoc}
         */
        @Override
        public void format(final LogEvent event, final StringBuilder toAppendTo) {
            Message msg = event.getMessage();
            if (msg instanceof StringBuilderFormattable) {
                ((StringBuilderFormattable) msg).formatTo(toAppendTo);
            } else if (msg != null) {
                toAppendTo.append(msg.getFormattedMessage());
            }
        }
    }

    private static final class FormattedMessagePatternConverter extends MessagePatternConverter {

        private final String[] formats;

        FormattedMessagePatternConverter(final String[] formats) {
            this.formats = formats;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void format(final LogEvent event, final StringBuilder toAppendTo) {
            Message msg = event.getMessage();
            if (msg instanceof StringBuilderFormattable) {
                if (msg instanceof MultiFormatStringBuilderFormattable) {
                    ((MultiFormatStringBuilderFormattable) msg).formatTo(formats, toAppendTo);
                } else {
                    ((StringBuilderFormattable) msg).formatTo(toAppendTo);
                }
            } else if (msg != null) {
                toAppendTo.append(msg instanceof MultiformatMessage
                        ? ((MultiformatMessage) msg).getFormattedMessage(formats)
                        : msg.getFormattedMessage());
            }
        }
    }

    private static final class LookupMessagePatternConverter extends MessagePatternConverter {
        private final MessagePatternConverter delegate;
        private final Configuration config;

        LookupMessagePatternConverter(final MessagePatternConverter delegate, final Configuration config) {
            this.delegate = delegate;
            this.config = config;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void format(final LogEvent event, final StringBuilder toAppendTo) {
            int start = toAppendTo.length();
            delegate.format(event, toAppendTo);
            int indexOfSubstitution = toAppendTo.indexOf("${", start);
            if (indexOfSubstitution >= 0) {
                config.getStrSubstitutor()
                        .replaceIn(event, toAppendTo, indexOfSubstitution, toAppendTo.length() - indexOfSubstitution);
            }
        }
    }

    private static final class RenderingPatternConverter extends MessagePatternConverter {

        private final MessagePatternConverter delegate;
        private final TextRenderer textRenderer;

        RenderingPatternConverter(final MessagePatternConverter delegate, final TextRenderer textRenderer) {
            this.delegate = delegate;
            this.textRenderer = textRenderer;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void format(final LogEvent event, final StringBuilder toAppendTo) {
            StringBuilder workingBuilder = new StringBuilder(80);
            delegate.format(event, workingBuilder);
            textRenderer.render(workingBuilder, toAppendTo);
        }

    }
}

@@ -2007,19 +2007,23 @@
  static 
-int
+boolean
  loadLoo
@@ -2105,62 +2105,8 @@
 or (
-int i = 0; i %3C options.length; i++) %7B%0A                
 fina
@@ -2125,17 +2125,17 @@
 ion 
-=
+:
  options
 %5Bi%5D;
@@ -2134,12 +2134,11 @@
 ions
-%5Bi%5D;
+) %7B
 %0A   
@@ -2217,17 +2217,20 @@
  return 
-i
+true
 ;%0A      
@@ -2284,10 +2284,13 @@
 urn 
--1
+false
 ;%0A  
@@ -3458,21 +3458,16 @@
 options)
- %3E= 0
 ;%0A      

Convert method to return a boolean