package eu.dnetlib.functionality.modular.ui;

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

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

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import eu.dnetlib.functionality.modular.ui.users.AccessLimited;
import eu.dnetlib.functionality.modular.ui.users.PermissionLevel;
import eu.dnetlib.functionality.modular.ui.users.User;

public class EntryPointsAggregator {
	
	@Autowired(required=false)
	private List<ModuleEntryPoint> entryPoints = Lists.newArrayList();;
	
	@Autowired(required=false)
	private List<AbstractMenu> otherMenus = Lists.newArrayList();

	public List<ModuleEntryPoint> getEntryPoints() {
		return entryPoints;
	}

	public void setEntryPoints(List<ModuleEntryPoint> entryPoints) {
		this.entryPoints = entryPoints;
	}
		
	public List<AbstractMenu> getMenus(User user) {
		final Map<String, ModulesMenu> map = new HashMap<String, ModulesMenu>();
		
		for (ModuleEntryPoint entry : entryPoints) {
			if (entry.isValidMenuEntry() && verifyAuthorization(entry, user)) {
				final String group = entry.getGroup();
				if (!map.containsKey(group)) {
					map.put(group, new ModulesMenu(group));
				}
				map.get(group).addEntry(entry);
			}
		}
		final List<AbstractMenu> items = Lists.newArrayList();
		
		for (AbstractMenu menu : otherMenus) {
			if (menu instanceof AccessLimited) {
				 if (verifyAuthorization((AccessLimited) menu, user) && menu.getEntries().size() > 0) {
					 items.add(menu);
				 }
			} else if (menu.getEntries().size() > 0) {
				items.add(menu);
			}
		}

		for (ModulesMenu item : map.values()) {
			item.complete();
			items.add(item);
		}
	
		Collections.sort(items);
		return items;
	}
	
	private boolean verifyAuthorization(AccessLimited entry, User user) {
		if (user.getPermissionLevels().contains(PermissionLevel.SUPER_ADMIN)) return true;
		
		return (Sets.intersection(user.getPermissionLevels(), entry.getPermissionLevels()).size() > 0);
	}
	
}
