package cn.ibizlab.codegen.templating.mustache;

import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template.Fragment;

import java.io.IOException;
import java.io.Writer;

/**
 * Replaces duplicate whitespace characters in a fragment with single space.
 *
 * Register:
 * <pre>
 * additionalProperties.put("lambdaPrefixWithHash", new PrefixWithHashLambda());
 * </pre>
 *
 * Use:
 * <pre>
 * {{#lambdaPrefixWithHash}}{{name}}{{/lambdaPrefixWithHash}}
 * </pre>
 */
public class PrefixWithHashLambda implements Mustache.Lambda {
    private static final String WITH_HASH = "\n#";

    private static final String NEWLINE_REGEX = "\\R";

    @Override
    public void execute(Fragment fragment, Writer writer) throws IOException {
        writer.write(fragment.execute().replaceAll(NEWLINE_REGEX, WITH_HASH));
    }

}
