TemplatingServiceImpl.java

/*
 * Copyright 2020 Global Crop Diversity Trust
 *
 * Licensed 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.gringlobal.service.impl;

import java.io.StringReader;
import java.io.StringWriter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import lombok.extern.slf4j.Slf4j;
import com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.KeepType;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.MutableDataHolder;
import com.vladsch.flexmark.util.data.MutableDataSet;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.util.StringToJavaTimeConverter;
import org.gringlobal.service.CodeValueTranslationService;
import org.gringlobal.service.TemplatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.google.common.base.Charsets;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 * The TemplatingServiceImpl using Mustache https://github.com/spullara/mustache.java
 * 
 * See http://mustache.github.io/mustache.5.html for manual.
 * 
 * - All variables are HTML escaped by default. If you want to return unescaped HTML, use the triple mustache: {{{name}}}.
 */
@Service
@Slf4j
public class TemplatingServiceImpl implements TemplatingService {
	
	/** The Constant flexmark OPTIONS. */
	private static final MutableDataHolder OPTIONS = new MutableDataSet()
		.set(Parser.REFERENCES_KEEP, KeepType.LAST)
		.set(Parser.HTML_BLOCK_PARSER, false)
//			.set(Parser.HTML_BLOCK_DEEP_PARSER, true)
//			.set(Parser.HTML_BLOCK_START_ONLY_ON_BLOCK_TAGS, true)
		.set(HtmlRenderer.INDENT_SIZE, 2)
		.set(HtmlRenderer.PERCENT_ENCODE_URLS, true)
//			.set(HtmlRenderer.ESCAPE_HTML, false)

		// for full GFM table compatibility add the following table extension options:
		.set(TablesExtension.COLUMN_SPANS, false)
		.set(TablesExtension.APPEND_MISSING_COLUMNS, true)
		.set(TablesExtension.DISCARD_EXTRA_COLUMNS, true)
		.set(TablesExtension.HEADER_SEPARATOR_COLUMN_MATCH, true)
		.set(Parser.EXTENSIONS, List.of(
			TablesExtension.create(),
			StrikethroughExtension.create()
		));

	private static final Parser parser = Parser.builder(OPTIONS).build();
	private static final HtmlRenderer renderer = HtmlRenderer.builder(OPTIONS).build();

	/**
	 * Extra functions available in templates:
	 * 
	 * - <code>URL</code>: URL encode the string
	 * - <code>URLPATH</code>: URL encodes path
	 * - <code>MARKDOWN</code> converts Markdown input to HTML
	 */
	private static final Map<String, Object> templateFunctions = Map.of(
		// URL encode
		"_url", (Function<String, String>) (input) -> StringUtils.isBlank(input) ? "" : UriUtils.encode(input, Charsets.UTF_8),
		"URL", (Function<String, String>) (input) -> StringUtils.isBlank(input) ? "" : UriUtils.encode(input, Charsets.UTF_8),

		"_urlpath", (Function<String, String>) (input) -> StringUtils.isBlank(input) ? "" : UriUtils.encodePath(input, Charsets.UTF_8),
		"URLPATH", (Function<String, String>) (input) -> StringUtils.isBlank(input) ? "" : UriUtils.encodePath(input, Charsets.UTF_8),

		"year", (Function<String, String>) TemplatingServiceImpl::formatToYear,
		"YEAR", (Function<String, String>) TemplatingServiceImpl::formatToYear,

		"formatDate", (Function<String, String>) TemplatingServiceImpl::formatDate,
		"FORMATDATE", (Function<String, String>) TemplatingServiceImpl::formatDate,

		"MARKDOWN", (Function<String, String>) TemplatingServiceImpl::formatMarkdown,

		// {{#RFIDBARCODE}}{{{inventory.barcode}}}{{/RFIDBARCODE}}
		"RFIDBARCODE", (Function<String, String>) TemplatingServiceImpl::rfidBarcode

	);

	/** Java Date.toString() produces: Fri Sep 06 05:21:48 CEST 2024 */
	private static final DateTimeFormatter JAVA_DATE_PATTERN = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss v yyyy");
	/** Instant seems to be formatted as: 2024-09-06 06:25:05.701 */
	private static final DateTimeFormatter MUSTACHE_PATTERN = new DateTimeFormatterBuilder().append(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
			.parseLenient()
			.appendOptional(DateTimeFormatter.ofPattern(".SSS")) // milliseconds seem to be very optional and dynamic
			.toFormatter();

	private final Cache<String, Mustache> templateCache = CacheBuilder.newBuilder().maximumSize(20).expireAfterAccess(10, TimeUnit.MINUTES).build();

	private final MustacheFactory mf = new DefaultMustacheFactory();

	@Autowired
	private CodeValueTranslationService codeValueService;
	@Autowired
	private MessageSource messageSource;

	@Override
	public String fillTemplate(String template, Map<String, Object> params) {
		return fillTemplate(compileTemplate(template), params);
	}

	@Override
	public String fillTemplate(Mustache mustache, Map<String, Object> params) {
		StringWriter swOut = new StringWriter();
		var paramsPlus = new HashMap<>(params);
		paramsPlus.putAll(templateFunctions);
		paramsPlus.putAll(Map.of(
			"codeValueTitle", (Function<String, String>)this::codeValueTitle,
			"i18n", (Function<String, String>)this::i18n
		));
		mustache.execute(swOut, paramsPlus);

		if (log.isTraceEnabled()) {
			log.trace(swOut.toString());
		}
		return swOut.toString();
	}

	@Override
	public Mustache compileTemplate(String template) {
		try {
			return templateCache.get(template, () -> {
				log.debug("Compiling Mustache template");
				return mf.compile(new StringReader(template), null);
			});
		} catch (ExecutionException e) {
			throw new RuntimeException(e);
		}
	}

	private static String formatToYear(String input) {
		if (StringUtils.isBlank(input)) return "";
		input = StringUtils.trim(input);
		try {
			var instant = parseDate(input);
			return String.valueOf(instant.atZone(LocaleContextHolder.getTimeZone().toZoneId()).getYear());
		} catch (Exception e) {
			var date = StringToJavaTimeConverter.StringToLocalDateConverter.INSTANCE.convert(input);
			return String.valueOf(date.getYear());
		}
	}

	private static Instant parseDate(String input) {
		try {
			return StringToJavaTimeConverter.StringToInstantConverter.INSTANCE.convert(input);
		} catch (Exception e1) {
			try {
				return MUSTACHE_PATTERN.parse(input, LocalDateTime::from).toInstant(ZoneOffset.UTC);
			} catch (Exception e2) {
				return JAVA_DATE_PATTERN.parse(input, ZonedDateTime::from).toInstant();
			}
		}
	}

	private static String formatDate(String input) {
		if (StringUtils.isBlank(input)) return "";
		input = StringUtils.trim(input);
		String[] inputParts = input.split("\\s+", 2); // Keep the timestamp togehter
		String pattern = inputParts[0];
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern).withZone(LocaleContextHolder.getTimeZone().toZoneId());
		if (inputParts.length == 2) {
			String date = inputParts[1];
			if (StringUtils.isBlank(date)) return "";
			// System.out.println("FORMATDATE " + input + " pattern=" + pattern + " date=" + date);
			var instant = parseDate(date);
			// System.out.println(" Instant: " + instant);
			return formatter.format(instant);
		} else {
			return "";
		}
	}

	private static String formatMarkdown(String input) {
		if (StringUtils.isBlank(input)) return "";
		final Node document = parser.parse(input);
		return renderer.render(document);
	}

	private static String rfidBarcode(String input) {
		return StringUtils.defaultIfBlank(input, "").replaceAll("[^a-f0-9A-F]", "").trim();
	}

	private String codeValueTitle(String input) {
		input = StringUtils.trim(input);
		String[] params = input.split(" ", 2);
		if (params.length != 2) {
			throw new IllegalArgumentException("Cannot find code value group and value in input: ".concat(input));
		}
		var cv = codeValueService.findTranslatedCodeValue(params[0], params[1], LocaleContextHolder.getLocale());
		String title = params[1];
		if (cv.isPresent()) {
			title = cv.get().getTitle();
		}
		return title;
	}

	private String i18n(String input) {
		log.trace("i18n: {}", input);
		return messageSource.getMessage(input, null, input, LocaleContextHolder.getLocale());
	}
}