/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */

package com.scytl.products.oscore.logging.core.layout;

import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;

import java.util.regex.Pattern;

public class EscapingPatternLayout extends PatternLayout {

    private final Pattern nEscapedPattern = Pattern.compile("\n");
    private final Pattern rEscapedPattern = Pattern.compile("\r");
    private final Pattern bEscapedPattern = Pattern.compile("\b");
    private final Pattern fEscapedPattern = Pattern.compile("\f");

    private final String nReplacement = "(n)";
    private final String rReplacement = "(r)";
    private final String bReplacement = "(b)";
    private final String fReplacement = "(f)";

    @Override
    public String format(LoggingEvent event) {
        String message = super.format(event);
        if (message.endsWith("\r\n")) {
            message = message.substring(0, message.length() - 2);
        } else if (message.endsWith("\n") || message.endsWith("\r")){
            message = message.substring(0, message.length() - 1);
        }

        message = rEscapedPattern.matcher(message).replaceAll(rReplacement);
        message = nEscapedPattern.matcher(message).replaceAll(nReplacement);
        message = bEscapedPattern.matcher(message).replaceAll(bReplacement);
        message = fEscapedPattern.matcher(message).replaceAll(fReplacement);

        return message + System.getProperty("line.separator");
    }
}
