package de.hsadmin.remote;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import de.hsadmin.core.model.AbstractEntity;
import de.hsadmin.mods.cust.Customer;
import de.hsadmin.mods.pac.BasePac;
import de.hsadmin.mods.pac.Hive;
import de.hsadmin.mods.pac.INetAddress;
import de.hsadmin.mods.pac.Pac;
import de.hsadmin.mods.pac.PacComponent;

public class PacRemote extends AbstractRemote {

	private static final DateFormat df = SimpleDateFormat.getDateInstance(DateFormat.SHORT);

	@Override
	protected void entity2map(AbstractEntity entity, Map<String, String> resultMap) {
		Pac pac = (Pac) entity;
		resultMap.put("name", pac.getName());
		resultMap.put("id", Long.toString(pac.getId()));
		resultMap.put("hive", pac.getHiveName());
		resultMap.put("customer", pac.getCustomer().getName());
		resultMap.put("curinetaddr", pac.getCurINetAddr().getInetAddr());
		resultMap.put("created", df.format(pac.getCreated()));
		resultMap.put("basepac", pac.getBasepac().getName());
		Set<PacComponent> pacComponents = pac.getPacComponents();
		StringBuffer bf = new StringBuffer();
		boolean empty = true;
		for (PacComponent comp : pacComponents) {
			if (comp.getQuantity() > 0) {
				if (!empty) {
					bf.append("; ");
				}
				bf.append(comp.getBaseComponent().getFeature());
				bf.append("=");
				bf.append(comp.getQuantity());
				empty = false;
			}
		}
		resultMap.put("components", bf.toString());
	}

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

	@Override
	protected void map2entity(Map<String, String> setParams, AbstractEntity entity) {
		Pac pac = (Pac) entity;
		BasePac basePac = pac.getBasepac();
		String basePacName = setParams.get("basepac");
		if ((basePac == null || basePac.getName() == null) && assertNotNull(basePacName)) {
			basePac = new BasePac();
			basePac.setName(basePacName);
			pac.setBasepac(basePac);
		}
		pac.setCreated(new Date());
		INetAddress curINetAddr = pac.getCurINetAddr();
		String inetAddrString = setParams.get("curinetaddr");
		if ((curINetAddr == null || curINetAddr.getInetAddr() == null) && assertNotNull(inetAddrString)) {
			curINetAddr = new INetAddress(inetAddrString);
			pac.setCurINetAddr(curINetAddr);
		}
		Customer customer = pac.getCustomer();
		String memberCode = setParams.get("customer");
		if (customer == null && assertNotNull(memberCode)) {
			customer = new Customer();
			customer.setName(memberCode);
			pac.setCustomer(customer);
		}
		Hive hive = pac.getHive();
		String hiveName = setParams.get("hive");
		if ((hive == null || hive.getName() == null) && assertNotNull(hiveName)) {
			hive = new Hive();
			hive.setName(hiveName);
			pac.setHive(hive);
		}
		pac.setName(setParams.get("name"));
	}

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

}
