package ch.elexis.core.jpa.model.adapter.mixin;

import java.util.Hashtable;
import java.util.Map;

import ch.elexis.core.jpa.entities.EntityWithExtInfo;
import ch.elexis.core.jpa.model.adapter.AbstractIdModelAdapter;
import ch.elexis.core.jpa.model.util.JpaModelUtil;

public class ExtInfoHandler {

	private AbstractIdModelAdapter<? extends EntityWithExtInfo> withExtInfo;

	public ExtInfoHandler(AbstractIdModelAdapter<? extends EntityWithExtInfo> withExtInfo) {
		this.withExtInfo = withExtInfo;
	}

	private Map<Object, Object> getExtInfoMap() {
		synchronized (withExtInfo) {
			byte[] bytes = withExtInfo.getEntity().getExtInfo();
			if (bytes != null) {
				return JpaModelUtil.extInfoFromBytes(bytes);
			} else {
				return new Hashtable<>();
			}
		}
	}

	public Object getExtInfo(Object key) {
		return getExtInfoMap().get(key);
	}

	public void setExtInfo(Object key, Object value) {
		synchronized (withExtInfo) {
			Map<Object, Object> extInfo = getExtInfoMap();

			if (value == null) {
				extInfo.remove(key);
			} else {
				extInfo.put(key, value);
			}
			withExtInfo.getEntityMarkDirty().setExtInfo(JpaModelUtil.extInfoToBytes(extInfo));
		}
	}

	/**
	 * @return modifications to this map are not persisted. Use
	 *         {@link #setExtInfo(Object, Object)} to handle persistent sets
	 */
	public Map<Object, Object> getMap() {
		return getExtInfoMap();
	}
}

@@ -91,16 +91,110 @@
 til.Map;
+%0Aimport java.util.stream.Collectors;%0A%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;
 %0A%0Aimport
@@ -1066,16 +1066,51 @@
 Map();%0A%0A
+%09%09%09debugLog(key, value, extInfo);%0A%0A
 %09%09%09if (v
@@ -1290,16 +1290,389 @@
 %09%09%7D%0A%09%7D%0A%0A
+%09private void debugLog(Object key, Object value, Map%3CObject, Object%3E extInfo) %7B%0A%09%09Logger logger = LoggerFactory.getLogger(getClass());%0A%09%09logger.info(%22Set key %5B%22 + key + %22%5D value %5B%22 + value + %22%5D of %5B%22 + withExtInfo + %22%5D%22);%0A%09%09logger.info(%22Current ExtInfo %22 + extInfo.keySet().stream().map(k -%3E k + %22=%22 + extInfo.get(k))%0A%09%09%09%09.collect(Collectors.joining(%22, %22, %22%7B%22, %22%7D%22)));%0A%09%7D%0A%0A
 %09/**%0A%09 *

add more debug logging to ExtInfoHandler