package eu.dnetlib.functionality.index.query;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import eu.dnetlib.functionality.index.client.IndexClientException;
import eu.dnetlib.functionality.index.utils.MDFormatReader;
import eu.dnetlib.functionality.index.utils.MetadataReference;
import eu.dnetlib.functionality.index.utils.ServiceTools;

public class Weights extends HashMap<MetadataReference, Map<String, String>> {

	private static final long serialVersionUID = -3517914310574484765L;

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

	@Autowired
	private ServiceTools serviceTools;

	@Autowired
	private MDFormatReader mdFormatReader;

	public Weights() {
		super();
	}

	public void initialize() throws IndexClientException {
		log.info("initializing weights");

		for (MetadataReference mdRef : serviceTools.listMDRefs()) {
			put(mdRef, mdFormatReader.getAttributeMap(mdRef, "weight"));
		}
		log.info("weights initialization completed");

	}

	@Override
	public Map<String, String> put(final MetadataReference mdRef, final Map<String, String> w) {
		log.info("[" + mdRef + "]" + " adding weights: " + w);
		return super.put(mdRef, w);
	}

	@Override
	public Map<String, String> get(final Object mdRef) {
		Map<String, String> map = super.get(mdRef);
		return map != null ? map : initAndGet(mdRef);
	}

	private Map<String, String> initAndGet(final Object mdRef) {
		try {
			initialize();
		} catch (IndexClientException e) {
			throw new RuntimeException(e);
		}
		return super.get(mdRef);
	}
}
