package eu.dnetlib.data.mdstore.modular.action;

import java.util.List;

import eu.dnetlib.data.mdstore.MDStoreServiceException;
import eu.dnetlib.data.mdstore.modular.MDFormatDescription;
import eu.dnetlib.data.mdstore.modular.MDStoreFeeder;
import eu.dnetlib.data.mdstore.modular.MDStoreUtils;
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;

public class FeedAction extends AbstractMDStoreAction {

	private static final Log log = LogFactory.getLog(FeedAction.class);
    private static final String layoutIndex = "store";

	private MDStoreFeeder feeder;

    @Autowired
    private MDStoreUtils mdstoreUtils;


	@Override
	public void executeAsync(final BlackboardServerHandler handler, final BlackboardJob job) throws MDStoreServiceException {

		final String mdId = job.getParameters().get("mdId");
		if ((mdId == null) || mdId.isEmpty()) throw new MDStoreServiceException("Blackboard param (mdId) is empty");

		final String epr = job.getParameters().get("epr");
		if ((epr == null) || epr.isEmpty()) throw new MDStoreServiceException("Blackboard param (mdId) is empty");

		String storingType = job.getParameters().get("storingType");
		if ((storingType == null) || storingType.isEmpty()) {
			storingType = "REFRESH";
		}
        String format = feeder.getDao().getMDStore(mdId).getFormat();
        List<MDFormatDescription> mdformats = mdstoreUtils.getField(format, layoutIndex);

        if (mdformats != null) {
            for (MDFormatDescription desc : mdformats) {
                log.info("name: " + desc.getName());
                log.info("xpath: " + desc.getXpath());
            }
        }


        feeder.feed(mdId, epr, storingType, true, mdformats, params -> {
	        job.getParameters().put("mdstoreSize", "" + params.get("mdstoreSize"));
	        job.getParameters().put("writeOps", "" + params.get("writeOps"));
	        completeWithSuccess(handler, job);
        }, e -> {
	        log.error("Error feeding mdstore: " + mdId, e);
	        completeWithFail(handler, job, e);
        });
	}

	public MDStoreFeeder getFeeder() {
		return feeder;
	}

	@Required
	public void setFeeder(final MDStoreFeeder feeder) {
		this.feeder = feeder;
	}

}
