package eu.dnetlib.enabling.inspector;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ModelAttribute;

import com.google.common.collect.Lists;

import eu.dnetlib.miscutils.collections.MappedCollection;
import eu.dnetlib.miscutils.functional.UnaryFunction;

/**
 * Common stuff for the inspector controllers.
 * 
 * @author marko
 * 
 */
public abstract class AbstractInspectorController { // NOPMD
	/**
	 * entry point groups
	 */
	@Resource
	List<EntryPointDescriptorGroup> entryPointsGroups;

	/**
	 * sort entry point groups according to the group name.
	 */
	@PostConstruct
	public void sortEntryPointGroups() {
		Collections.sort(entryPointsGroups, new Comparator<EntryPointDescriptorGroup>() {

			@Override
			public int compare(EntryPointDescriptorGroup o1, EntryPointDescriptorGroup o2) {
				return o1.getName().compareTo(o2.getName());
			}
		});
	}

	/**
	 * common base url for all inspector pages.
	 * 
	 * @param request
	 *            http request
	 * @return base url
	 */
	@ModelAttribute("baseUrl")
	public String baseUrl(final HttpServletRequest request) {
		return request.getContextPath() + "/mvc/inspector";
	}

	@ModelAttribute("entryPointGroups")
	public List<EntryPointDescriptorGroup> entryPointGroups() {
		return entryPointsGroups;
	}
	/**
	 * Obtain a list of entry points, ordered by groups.
	 * 
	 * @return
	 */
	@ModelAttribute("entryPoints")
	public List<EntryPointDescriptorModel> entryPoints(final HttpServletRequest request) {
		final String currentRelativeUrl = request.getPathInfo().replaceAll("/inspector/(.*\\.do).*", "$1");
		
		ArrayList<EntryPointDescriptorModel> all = new ArrayList<EntryPointDescriptorModel>();

		UnaryFunction<EntryPointDescriptorModel, EntryPointDescriptor> mapper = new UnaryFunction<EntryPointDescriptorModel, EntryPointDescriptor>() {

			@Override
			public EntryPointDescriptorModel evaluate(EntryPointDescriptor arg) {
				return new EntryPointDescriptorModel(arg.getName(), arg.getRelativeUrl(), currentRelativeUrl.equals(arg.getRelativeUrl()), arg.isHiddenAsDefault());
			}
		};

		for (EntryPointDescriptorGroup group : entryPointsGroups)
			all.addAll(Lists.newArrayList(new MappedCollection<EntryPointDescriptorModel, EntryPointDescriptor>(group.getDescriptors(), mapper)));
		return all;
	}
}
