package de.hsadmin.remote;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import de.hsadmin.core.model.AbstractEntity;
import de.hsadmin.core.model.Transaction;
import de.hsadmin.mods.email.EMailAlias;

public class EMailAliasRemote extends AbstractRemote {

	@Override
	protected void entity2map(Transaction tx, AbstractEntity entity, Map<String, Object> map) {
		EMailAlias alias = (EMailAlias) entity;
		String id = Long.toString(alias.getId());
		String name = alias.getName();
		String pac = alias.getPac().getName();
		String target = alias.getTarget();
		map.put("id", id);
		map.put("name", name);
		map.put("pac", pac);
		StringTokenizer tokenizer = new StringTokenizer(target, ",");
		List<String> tokenList = new ArrayList<String>(); 
		while (tokenizer.hasMoreTokens()) {
			tokenList.add(tokenizer.nextToken().trim());
		}
		map.put("target", tokenList);
	}

	@Override
	protected Class<? extends AbstractEntity> getEntityClass() {
		return EMailAlias.class;
	}

	@Override
	protected void map2entity(Transaction tx, Map<String, Object> map, AbstractEntity entity) {
		EMailAlias alias = (EMailAlias) entity;
		String name = (String) map.get("name");
		if (assertNotNull(name)) {
			alias.setName(name);
		}
		Object l = map.get("target");
		if (l instanceof String) {
			String target = (String) l;
			if (assertNotNull(target)) {
				alias.setTarget(target);
			} 
		}
		if (l instanceof Object[]) {
			StringBuffer tBuff = new StringBuffer();
			Object[] targetObjArray = (Object[]) l;
			for (int idx=0; idx<targetObjArray.length; idx++) {
				Object targetObj = targetObjArray[idx];
				if (targetObj instanceof String) {
					if (tBuff.length() > 0) {
						tBuff.append(',');
					}
					tBuff.append((String) targetObj);
				}
			}
			alias.setTarget(tBuff.toString());
		}
	}

	@Override
	protected void regularizeKeys(Map<String, String> whereParams) {
		replaceKey(whereParams, "pac", "pac.name");
	}

}
