package eu.dnetlib.enabling.inspector;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import com.google.common.collect.Lists;

import eu.dnetlib.enabling.tools.ResourceIdentifierResolver;

/**
 * This class allows to create links between profiles.
 *  
 * @author claudio
 *
 */
public class ResourceLinkTool {

	/**
	 * Regular expression used to match resource ids.
	 */
	private static String REGEX = "([a-zA-Z0-9]+\\-)+[a-zA-Z0-9]+_[a-zA-Z0-9]+";
	
	/**
	 * Base url.
	 */
	private String serviceBaseUrl;
	
	/**
	 * ResourceIdentifierResolver.
	 */
	private ResourceIdentifierResolver resolver;
	
	/**
	 * Method parses a profile and transforms all the ids into an html link
	 * 
	 * @param profile
	 * 			the given profile.
	 * @return
	 * 			the linkfied profile
	 */
	public String linkfyToHtml(final String profile) {
		String tmp = new String(profile);		
		for (String id : enumerateIds(profile))
			tmp = tmp.replaceAll(id, toLink(id));

		return tmp;
	}
	
	/**
	 * Performs the actual transformation.
	 * 
	 * @param id
	 * @return
	 */
	protected String toLink(String id) {
		return "<a href=\"" + serviceBaseUrl + 
					"/inspector/index.do/db/DRIVER/" + 
					getResolver().getCollectionName(id) + "/" + 
					getResolver().getFileName(id) + "/show\">" + id + "</a>";
	}

	/**
	 * Lists all the ids in the given profile.
	 * 
	 * @param profile
	 * @return
	 */
	private List<String> enumerateIds(final String profile) {
		List<String> ids = Lists.newArrayList(); 
		String tmp = new String(profile);
		
		Pattern p = Pattern.compile(REGEX);
		Matcher m = p.matcher(tmp);
		
		while(m.find())
			ids.add(m.group());
		return ids;
	}

	@Required
	public void setResolver(ResourceIdentifierResolver resolver) {
		this.resolver = resolver;
	}

	public ResourceIdentifierResolver getResolver() {
		return resolver;
	}

	@Required
	public void setServiceBaseUrl(String serviceBaseUrl) {
		this.serviceBaseUrl = serviceBaseUrl;
	}

	public String getServiceBaseUrl() {
		return serviceBaseUrl;
	}
}
