package de.hsadmin.mods.email;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import de.hsadmin.core.model.AbstractModuleImpl;
import de.hsadmin.core.model.AuthorisationException;
import de.hsadmin.core.model.AbstractEntity;
import de.hsadmin.core.model.HSAdminException;
import de.hsadmin.mods.dom.Domain;

public class EMailAddressModuleImpl extends AbstractModuleImpl {

	@Override
	public List<AbstractEntity> search(Class<? extends AbstractEntity> entityClass,
			String condition, String orderBy) throws HSAdminException {
		if (orderBy == null || orderBy.length() == 0) {
			orderBy = "ORDER BY obj.domain.name ASC, obj.subdomain ASC, obj.localpart ASC";
		}
		return super.search(entityClass, condition, orderBy);
	}

	@Override
	public AbstractEntity add(AbstractEntity newEntity) throws HSAdminException {
		EntityManager em = getTransaction().getEntityManager();
		EMailAddress adr = (EMailAddress) newEntity;
		if (adr.getTarget() == null || adr.getTarget().length() == 0) {
			throw new HSAdminException("target required");
		}
		if (adr.getLocalpart() == null) {
			adr.setLocalpart("");
		}
		if (adr.getDomain() == null
				|| adr.getDomain().getName() == null
				|| adr.getDomain().getName().length() == 0) {
			throw new HSAdminException("domain required");
		}
		Query qDomain = em.createQuery("SELECT d FROM Domains d WHERE d.name = :domName");
		qDomain.setParameter("domName", adr.getDomain().getName());
		Domain dom = (Domain) qDomain.getSingleResult();
		adr.setDomain(dom);
		return super.add(newEntity);
	}

	@Override
	public AbstractEntity update(AbstractEntity existingEntity) throws HSAdminException {
		EMailAddress detachedAddr = (EMailAddress) existingEntity;
		EntityManager em = getTransaction().getEntityManager();
		EMailAddress attachedAddr = em.find(EMailAddress.class, detachedAddr.getId());
		String domain = detachedAddr.getDomain().getName();
		if (domain != null && !domain.equals(attachedAddr.getDomain().getName())) {
			detachedAddr.setDomain(attachedAddr.getDomain());
			throw new AuthorisationException(getLoginUser(), "update", detachedAddr, "domain");
		}
		String subdomain = detachedAddr.getSubdomain();
		if (subdomain != null && !subdomain.equals(attachedAddr.getSubdomain())) {
			detachedAddr.setSubdomain(attachedAddr.getSubdomain());
			throw new AuthorisationException(getLoginUser(), "update", detachedAddr, "subdomain");
		}
		String localPart = detachedAddr.getLocalpart();
		if (localPart != null && !localPart.equals(attachedAddr.getLocalpart())) {
			detachedAddr.setLocalpart(attachedAddr.getLocalpart());
			throw new AuthorisationException(getLoginUser(), "update", detachedAddr, "localpart");
		}
		String target = detachedAddr.getTarget();
		if (target == null) {
			throw new HSAdminException("target required");
		}
		attachedAddr.setTarget(target);
		return super.update(attachedAddr);
	}
	
}
