package eu.dnetlib.functionality.index.solr.cql;

import java.util.Map;

import eu.dnetlib.functionality.cql.CqlValueTransformerMap;
import eu.dnetlib.functionality.index.model.Any.ValueType;
import eu.dnetlib.miscutils.functional.IdentityFunction;
import eu.dnetlib.miscutils.functional.UnaryFunction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.common.SolrException;

/**
 * This class maps the fields in the given index schema with a transformation rule.
 * 
 * @author marko
 * 
 */
public class SolrTypeBasedCqlValueTransformerMap implements CqlValueTransformerMap {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(SolrTypeBasedCqlValueTransformerMap.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * Index schema.
	 */
	private final Map<String, ValueType> schema;

	/**
	 * Map of functions.
	 */
	private final Map<String, UnaryFunction<String, String>> transformerMap;

	/**
	 * Create value transformer map bound to a specific schema
	 * @param schema
	 * @param transformerMap
	 */
	public SolrTypeBasedCqlValueTransformerMap(final Map<String, ValueType> schema, final Map<String, UnaryFunction<String, String>> transformerMap) {
		this.schema = schema;
		this.transformerMap = transformerMap;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see CqlValueTransformerMap#transformerFor(String)
	 */
	@Override
	public UnaryFunction<String, String> transformerFor(final String fieldName) {
		try {
			final ValueType field = schema.get(fieldName);

			if (field != null) {
				UnaryFunction<String, String> res = transformerMap.get(field.name());
				if (res != null) {
					return res;
				}
			}
		} catch (SolrException e) {
			log.debug("cannot find field", e);
		}
		return new IdentityFunction<String>();
	}

}
