package metalexer.metalexer;

public class EscapeHelper {
    private EscapeHelper() {}
    
    //escape %} as %%}
    public static String escapeDeclRegion(String original) {
        return escapeAllButTerminal(original, "%}", "%%}");
    }
    
    //escape %init} as %%init}
    public static String escapeInitRegion(String original) {
        return escapeAllButTerminal(original, "%init}", "%%init}");
    }
    
    //escape %append} as %%append}
    public static String escapeAppendRegion(String original) {
        return escapeAllButTerminal(original, "%append}", "%%append}");
    }
    
    //escape %appendWithStartDelim} as %%appendWithStartDelim}
    public static String escapeAppendWithStartDelimRegion(String original) {
        return escapeAllButTerminal(original, "%appendWithStartDelim}", "%%appendWithStartDelim}");
    }
    
    //escape :} as %:}
    public static String escapeAction(String original) {
        return escapeAllButTerminal(original, ":}", "%:}");
    }
    
    //escape LF as \n, CR as \r
    public static String escapeString(String original) {
        return original.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
    }
    
    private static String escapeAllButTerminal(String original, String from, String to) {
        if(original.endsWith(from)) {
            String tmp = original.substring(0, original.length() - from.length());
            return tmp.replaceAll(from, to) + from;
        } else {
            return original.replaceAll(from, to);
        }
    }
}
