package eu.dnetlib.functionality.index.model.util;

import java.util.Iterator;
import java.util.Map.Entry;

import eu.dnetlib.functionality.index.model.AnyMap;
import eu.dnetlib.functionality.index.model.DataFactory;
import eu.dnetlib.functionality.index.model.InvalidValueTypeException;
import eu.dnetlib.functionality.index.model.Value;
import eu.dnetlib.functionality.index.model.impl.DefaultDataFactoryImpl;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;

/**
 * The Class AnySolrUtil.
 */
public class AnySolrUtil extends AnyUtil {

	/**
	 * Convert named list to any map.
	 * 
	 * @param list
	 *            the list
	 * @param map
	 *            the map
	 * @return the any map
	 */
	@SuppressWarnings("unchecked")
	public static AnyMap convertNamedListToAnyMap(final NamedList<Object> list, final AnyMap map) {
		final Iterator<Entry<String, Object>> it = list.iterator();
		while (it.hasNext()) {
			Entry<String, Object> entry = it.next();
			final String key = entry.getKey();
			final Object obj = entry.getValue();
			if (obj instanceof NamedList<?>) {
				final AnyMap subMap = map.getMap(key, true);
				convertNamedListToAnyMap((NamedList<Object>) obj, subMap);
			} else if (obj instanceof SolrDocumentList) {
				SolrDocumentList docList = (SolrDocumentList) obj;
				AnyMap response = DataFactory.DEFAULT.createAnyMap();
				response.put("numFound", docList.getNumFound());
				response.put("start", docList.getStart());
				response.put("maxScore", docList.getMaxScore());
				response.put("docs", objectToAny(obj));
				map.put("response", response);
			} else {
				try {
					final Value value = DataFactory.DEFAULT.autoConvertValue(obj);
					map.put(key, value);
				} catch (InvalidValueTypeException exception) {
					; // skip
				}
			}
		}
		return map;
	}

	/**
	 * Convert named list to any map.
	 * 
	 * @param list
	 *            the list
	 * @return the any map
	 */
	public static AnyMap convertNamedListToAnyMap(final NamedList<Object> list) {
		return convertNamedListToAnyMap(list, DefaultDataFactoryImpl.INSTANCE.createAnyMap());
	}

}
