package eu.dnetlib.miscutils.templates;

import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Map;

import org.antlr.stringtemplate.StringTemplate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import eu.dnetlib.clients.is.InformationServiceClient;
import eu.dnetlib.exceptions.DnetGenericException;

@Component
public class TemplateUtil {

	@Autowired
	private InformationServiceClient isClient;

	private static final Log log = LogFactory.getLog(TemplateUtil.class);

	public Map<String, String> processTemplateProfile(final String profileId, final Map<String, Object> map) throws DnetGenericException {

		final String profile = isClient.getProfile(profileId);

		try {
			final Document doc = (new SAXReader()).read(new StringReader(profile));

			final Map<String, String> res = new LinkedHashMap<>();

			for (final Object o : doc.selectNodes("//TEMPLATE")) {
				final String type = ((Node) o).valueOf("@type");
				final String language = ((Node) o).valueOf("@language");
				final String template = ((Node) o).getText();

				switch (language) {
				case "StringTemplate":
					final StringTemplate st = new StringTemplate(template);
					st.setAttributes(map);
					res.put(type, st.toString());
					break;
				default:
					log.error("Unknown template language: " + language);
					throw new DnetGenericException("Unknown template language: " + language);
				}
			}

			if (res.isEmpty()) {
				log.error("Empty result for template: " + profileId);
				throw new DnetGenericException("Empty result for template: " + profileId);
			}

			return res;
		} catch (final DocumentException e) {
			log.error("Error processing template: " + profileId, e);
			throw new DnetGenericException("Error processing template: " + profileId, e);
		}

	}

}
