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.TicketAuthentication;
import de.hsadmin.core.model.Transaction;
import de.hsadmin.core.util.Config;
import de.hsadmin.mods.dom.Domain;

public class RoleRemote implements IRemote {

	private TicketAuthentication authentication;

	public RoleRemote() {
		authentication = new TicketAuthentication();
	}
	
	@Override
	public List<Map<String, String>> search(String runAsUser, String ticket,
			Map<String, String> whereParams) throws HSAdminException {
		String user = runAsUser;
		Transaction transaction = new Transaction(user);
		if (authentication.login(user, ticket)) {
			String role = "USER";
			String accoutPrefixCustomer = Config.getInstance().getProperty("accountprefix.customer");
			String accoutPrefixHostmaster = Config.getInstance().getProperty("accountprefix.hostmaster");
			String pacName = transaction.getLoginUser().getPac().getName();
			if (accoutPrefixCustomer.equals(pacName)) {
				role = "CUSTOMER";
			}
			if (accoutPrefixHostmaster.equals(pacName)) {
				role = "HOSTMASTER";
			}
			if (user.equals(pacName)) {
				role = "PAC_ADMIN";
			}
			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, String>> result = new ArrayList<Map<String,String>>();
			Map<String, String> record = new HashMap<String, String>();
			record.put("role", role);
			result.add(record);
			transaction.close();
			return result;
		} else {
			transaction.close();
			throw new AuthenticationException("authentication failed");
		}
	}

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

	@Override
	public List<Map<String, String>> update(String runAsUser, String ticket,
			Map<String, String> 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");
	}

}
