package eu.dnetlib;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import freemarker.template.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ui.freemarker.SpringTemplateLoader;

@Component
@ConfigurationProperties(prefix = "msro.worker")
public class WorkerProperties {

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

	private final ObjectMapper mapper = new ObjectMapper();

	@Min(1)
	@Max(1024)
	private int maxSize;

	@NotNull
	private String datasourceProtocolsJson;

	@NotNull
	private String datasourceTypologiesJson;

	@Autowired
	private Configuration freemarkerCfg;

	private String templatePath = "templates/dnetprofiles";

	@PostConstruct
	public void init() {
		log.info(String.format("initialising freemarker configuration %s to load templates from %s", freemarkerCfg, templatePath));
		freemarkerCfg.setTemplateLoader(new SpringTemplateLoader(new DefaultResourceLoader(), templatePath));
	}

	public String getDatasourceProtocolsJson() {
		return datasourceProtocolsJson;
	}

	public void setDatasourceProtocolsJson(final String datasourceProtocolsJson) {
		this.datasourceProtocolsJson = datasourceProtocolsJson;
	}

	public String getDatasourceTypologiesJson() {
		return datasourceTypologiesJson;
	}

	public void setDatasourceTypologiesJson(final String datasourceTypologiesJson) {
		this.datasourceTypologiesJson = datasourceTypologiesJson;
	}

	public int getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(final int maxSize) {
		this.maxSize = maxSize;
	}

	public List<Map<String, String>> getDatasourceTypologies() {
		try {
			return mapper.readValue(datasourceTypologiesJson, List.class);
		} catch (final IOException e) {
			log.warn("Invalid JSON property: " + datasourceTypologiesJson, e);
			return new ArrayList<>();
		}
	}

	public List<Map<String, String>> getDatasourceProtocols() {
		try {
			return mapper.readValue(datasourceProtocolsJson, List.class);
		} catch (final IOException e) {
			log.warn("Invalid JSON property: " + datasourceProtocolsJson, e);
			return new ArrayList<>();
		}
	}
}
