package eu.dnetlib.index.utils;

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

import eu.dnetlib.clients.index.model.AnyMap;
import eu.dnetlib.clients.index.model.DataFactory;
import eu.dnetlib.clients.index.model.InvalidValueTypeException;
import eu.dnetlib.clients.index.model.Value;
import eu.dnetlib.clients.index.model.impl.DefaultDataFactoryImpl;
import eu.dnetlib.clients.index.model.util.AnyUtil;
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) {

				}
			}
		}
		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());
	}

}
