package de.hsadmin.remote;

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

import de.hsadmin.core.model.AbstractEntity;
import de.hsadmin.core.model.AuthenticationException;
import de.hsadmin.core.model.GenericModuleImpl;
import de.hsadmin.core.model.HSAdminException;
import de.hsadmin.core.model.Transaction;
import de.hsadmin.core.util.Config;
import de.hsadmin.mods.dom.Domain;
import de.hsadmin.mods.pac.Pac;

public class RoleRemote implements IRemote {

	@Override
	public List<Map<String, Object>> search(String runAsUser, String ticket,
			Map<String, String> whereParams) throws HSAdminException {
		String user = runAsUser;
		Transaction transaction = new Transaction(user);
		if (transaction.login(user, ticket)) {
			String role = "USER";
			String accoutPrefixCustomer = Config.getInstance().getProperty("accountprefix.customer");
			String accoutPrefixHostmaster = Config.getInstance().getProperty("accountprefix.hostmaster");
			Pac pac = transaction.getLoginUser().getPac();
			String pacName = pac.getName();
			if (accoutPrefixCustomer.equals(pacName)) {
				role = "CUSTOMER";
			}
			if (accoutPrefixHostmaster.equals(pacName)) {
				role = "HOSTMASTER";
			}
			if (user.equals(pacName)) {
				if (pac.isDynamicWeb()) {
					role = "PAC_ADMIN_DW";
				} else {
					role = "PAC_ADMIN_SW";
				}
			}
			if (role.equals("USER")) {
				GenericModuleImpl module = new GenericModuleImpl(transaction);
				List<AbstractEntity> list = module.search(Domain.class, "obj.user.name = '" + user + "'", null);
				if (list != null && list.size() > 0) {
					role = "DOM_ADMIN";
				}
			}
			List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
			Map<String, Object> record = new HashMap<String, Object>();
			record.put("role", role);
			result.add(record);
			transaction.close();
			return result;
		} else {
			transaction.close();
			throw new AuthenticationException("authentication failed");
		}
	}

	@Override
	public Map<String, Object> add(String runAsUser, String ticket,
			Map<String, Object> setParams) throws HSAdminException {
		throw new HSAdminException("not implemented");
	}

	@Override
	public List<Map<String, Object>> update(String runAsUser, String ticket,
			Map<String, Object> setParams, Map<String, String> whereParams)
			throws HSAdminException {
		throw new HSAdminException("not implemented");
	}

	@Override
	public void delete(String runAsUser, String ticket,
			Map<String, String> whereParams) throws HSAdminException {
		throw new HSAdminException("not implemented");
	}

}
