package de.hsadmin.mods.dom;

import java.util.Date;
import java.util.LinkedList;
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.core.util.DNSCheck;
import de.hsadmin.mods.dom.Domain.Status;
import de.hsadmin.mods.email.EMailAddress;
import de.hsadmin.mods.pac.Pac;
import de.hsadmin.mods.user.UnixUser;

public class DomainModuleImpl extends AbstractModuleImpl {
	
	private static final long serialVersionUID = -3991273357778898175L;

	@Override
	public AbstractEntity initialize(AbstractEntity newEntity) throws AuthorisationException {
		AbstractEntity newDom = super.initialize(newEntity);
		if (newDom instanceof Domain) {
			((Domain) newDom).setUser(getLoginUser());
			return newDom;
		}
		return null;
	}

	@Override
	public AbstractEntity find(Class<? extends AbstractEntity> entityClass, Object key) throws HSAdminException {
		// do query
		AbstractEntity res = super.find(entityClass, key);

		// check access rights
		needsReadAccessOn(res, "find");

		// return clean result
		return res;
	}

	@Override
	public AbstractEntity findByString(Class<? extends AbstractEntity> entityClass, String key)
			throws HSAdminException {
		// do query
		AbstractEntity res = super.findByString(entityClass, key);

		// check access rights
		if (res != null)
			needsReadAccessOn(res, "findByString");

		// return clean result
		return res;
	}

	@Override
	public List<AbstractEntity> search(Class<? extends AbstractEntity> entityClass, String condition, String orderBy) throws HSAdminException {
		// do query
		if (orderBy == null || orderBy.length() == 0) {
			orderBy = "ORDER BY obj.name ASC";
		}
		List<AbstractEntity> res = super.search(entityClass, condition, orderBy);
		List<AbstractEntity> ret = new LinkedList<AbstractEntity>();

		// remove entities where login user has no access rights
		for (AbstractEntity entity : res) {
			try {
				needsReadAccessOn(entity, "search");
				ret.add(entity);
			} catch (AuthorisationException exc) {
			} // ignore
		}

		// return clean result
		return ret;
	}

	@Override
	public AbstractEntity add(AbstractEntity newEntity) throws HSAdminException {
		Domain dom = (Domain) newEntity;
		Date now = new Date();
		dom.setFiled(now);
		dom.setStatus(Status.SELF);
		dom.setStatusChanged(now);
		dom.setDnsMaster("dns1.hostsharing.net");
		if (dom.getName() == null || dom.getName().length() == 0) {
			throw new HSAdminException("domain name required");
		}
		UnixUser admin = dom.getUser();
		if (admin == null || admin.getName() == null || admin.getName().length() == 0) {
			throw new HSAdminException("domain admin required");
		}
		EntityManager em = getTransaction().getEntityManager();

		// search for domains superior to dom
		Query domainQuery = em.createQuery("SELECT d FROM Domains d WHERE d.name = :domainName");
		String superior = dom.getName();
		while (superior.contains(".")) {
			superior = superior.substring(superior.indexOf('.') + 1);
			domainQuery.setParameter("domainName", superior);
			if (domainQuery.getResultList().size() > 0) {
				DNSCheck dnsCheck = new DNSCheck(dom.getDnsMaster());
				if (dnsCheck.checkDomain(dom.getName())) {
					break;
				} else {
					throw new HSAdminException("domain " + dom.getName() + " is not delegated to " + dom.getDnsMaster());
				}
			}
		}
		
		Query adminQuery = em.createQuery("SELECT u FROM UnixUsers u WHERE u.name = :adminName");
		adminQuery.setParameter("adminName", admin.getName());
		dom.setUser((UnixUser) adminQuery.getSingleResult());
		needsWriteAccessOn(newEntity, "add");
//		Entity addedEntity = super.add(dom);
//		Domain addedDomain = (Domain) addedEntity;
		em.persist(dom);
		String[] emailAddresses = new String[] { "abuse", "postmaster", "webmaster" };
		for (String emailLocalpart : emailAddresses) {
			EMailAddress eMailAddress = new EMailAddress(emailLocalpart, "", dom, admin.getName());
			em.persist(eMailAddress);
		}
		return super.add(dom);
	}

	@Override
	public AbstractEntity update(AbstractEntity existingEntity) throws HSAdminException {
		Domain dom = (Domain) existingEntity;
		if (dom.getName() == null || dom.getName().length() == 0) {
			throw new HSAdminException("domain name required");
		}
		UnixUser admin = dom.getUser();
		if (admin == null || admin.getName() == null || admin.getName().length() == 0) {
			throw new HSAdminException("domain admin required");
		}
		if (admin.getPac() == null) {
			EntityManager em = getTransaction().getEntityManager();
			Query query = em.createQuery("SELECT u FROM UnixUsers u WHERE u.name = :adminName");
			query.setParameter("adminName", admin.getName());
			dom.setUser((UnixUser) query.getSingleResult());
		}
		needsWriteAccessOn(existingEntity, "update");
		throw new AuthorisationException(getLoginUser(), "update", existingEntity);
	}

	@Override
	public void delete(AbstractEntity existingEntity) throws HSAdminException {
		needsWriteAccessOn(existingEntity, "delete");
		Domain dom = (Domain) existingEntity;
		EntityManager em = getTransaction().getEntityManager();
		Query query = em.createQuery("SELECT adr FROM " + EMailAddress.class.getAnnotation(javax.persistence.Entity.class).name() 
				+ " adr WHERE adr.domain.name='" + dom.getName() + "'");
		List<?> resultList = query.getResultList();
		for (Object obj : resultList) {
			EMailAddress eMailAddress = (EMailAddress) obj;
			em.remove(eMailAddress);
		}
		super.delete(existingEntity);
	}

	private void needsReadAccessOn(AbstractEntity ent, String method) throws AuthorisationException {
		if (ent instanceof Domain) {
			Domain dom = (Domain) ent;
			String aLoginUserName = getLoginUser().getName();
			UnixUser domUser = dom.getUser();
			Pac domPac = domUser.getPac();
			boolean isDomAdmin = aLoginUserName.equals(domUser.getName());
			boolean isPacAdmin = aLoginUserName.equals(domPac.getName());
			boolean isCustomer = aLoginUserName.equals(domPac.getCustomer().getName());
			boolean isHostmaster = getLoginUser().hasHostmasterRole();
			if (!isDomAdmin && !isPacAdmin && !isCustomer && !isHostmaster) {
				throw new AuthorisationException(getLoginUser(), method, dom);
			}
		} else {
			throw new AuthorisationException(getLoginUser(), method, ent);
		}
	}

	private void needsWriteAccessOn(AbstractEntity ent, String method) throws AuthorisationException {
		if (ent instanceof Domain) {
			Domain dom = (Domain) ent;
			String aLoginUserName = getLoginUser().getName();
			UnixUser domUser = dom.getUser();
			Pac domPac = domUser.getPac();
			boolean isPacAdmin = aLoginUserName.equals(domPac.getName());
			boolean isCustomer = aLoginUserName.equals(domPac.getCustomer().getName());
			if (!isPacAdmin && !isCustomer)
				throw new AuthorisationException(getLoginUser(), method, dom);
		} else {
			throw new AuthorisationException(getLoginUser(), method, ent);
		}
	}

}
