package de.jottyfan.camporganizer.module.business.privileges;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import de.jottyfan.camporganizer.db.jooq.enums.EnumCamprole;
import de.jottyfan.camporganizer.module.business.camp.model.CampBean;
import de.jottyfan.camporganizer.module.business.privileges.model.BusinessPrivilegesBean;
import de.jottyfan.camporganizer.module.business.privileges.model.ProfileBean;

/**
 *
 * @author jotty
 *
 */
@Service
public class BusinessPrivilegesService {
	@Autowired
	private BusinessPrivilegesRepository gateway;

	public Map<Integer, CampBean> getPrivileges() {
		List<BusinessPrivilegesBean> list = gateway.getPrivileges();
		Map<Integer, CampBean> camps = new HashMap<>();
		for (BusinessPrivilegesBean bean : list) {
			CampBean campBean = camps.get(bean.getFkCamp());
			if (campBean == null) {
				campBean = new CampBean();
				camps.put(bean.getFkCamp(), campBean);
			}
			campBean.setPk(bean.getFkCamp());
			campBean.setName(bean.getCampName());
			campBean.setYear(bean.getCampYear());
			ProfileBean profileBean = new ProfileBean();
			profileBean.setPk(bean.getFkProfile());
			profileBean.setForename(bean.getForename());
			profileBean.setSurname(bean.getSurname());
			profileBean.setUsername(bean.getUsername());
			profileBean.setDuedate(bean.getDuedate());
			campBean.getProfiles().add(profileBean);
		}
		return camps;
	}

	public List<ProfileBean> getProfiles(EnumCamprole... allowed) {
		Set<String> set = new HashSet<>();
		for (EnumCamprole role : allowed) {
			set.add(role.getLiteral());
		}
		return gateway.getProfiles(allowed == null ? null : set);
	}

	public void add(BusinessPrivilegesBean bean) {
		gateway.add(bean);
	}

	public void remove(BusinessPrivilegesBean bean, String currentUser) {
		gateway.remove(bean, currentUser);
	}
}
