package fr.opensagres.xdocreport.template.freemarker.internal;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import foundation.dao.PackageStringMap;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.utils.TemplateUtils;

public class XDocFreemarkerContext implements IContext {
	
	protected static Logger logger;
	private Map<String, Object> contextMap;
	private Map<String, String> dataMap;

	static {
	    logger = LogManager.getLogger(XDocFreemarkerContext.class);
	}
	
	public XDocFreemarkerContext() {
		this(new HashMap<String, Object>());
	}

	public XDocFreemarkerContext(Map<String, Object> contextMap) {
		this.contextMap = contextMap;
	}

	public Object put(String key, Object value) {
		Object result = TemplateUtils.putContextForDottedKey(this, key, value);
		
		if (result == null) {
			return this.contextMap.put(key, value);
		}
		
		return result;
	}

	public Object get(String key) {
		Object result = this.contextMap.get(key);
		
		if (result != null) {
			return result;
		}
		
		if (dataMap == null || key.startsWith("__")) {
			return null;
		}
		
		int pos = key.indexOf(PackageStringMap.Spliter);
		if (pos > 0) {
			result = dataMap.get(key);
		}
		
		return result;
	}

	public void putMap(Map<String, Object> contextMap) {
		this.contextMap.putAll(contextMap);
	}

	public Map<String, Object> getContextMap() {
		return this.contextMap;
	}

	public void setDataMap(Map<String, String> dataMap) {
		this.dataMap = dataMap;
	}
	
}