package eu.dnetlib.oai.actions;

import java.util.Arrays;

import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
import eu.dnetlib.oai.mongo.MongoPublisherStore;
import eu.dnetlib.oai.mongo.MongoPublisherStoreDAO;
import eu.dnetlib.oai.utils.OAIParameterNames;
import eu.dnetlib.rmi.provision.OaiPublisherRuntimeException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Create the indices on fields specified in the job parameter 'oai_index_fieldNames'.
 * Example: field1,field2 -- one compound index on the given two fields
 * field1,field2;field3,field4 -- two compound indices: one on field1 and field2, the other on field3 and field4
 * field5;field6 -- two indices: one on field5, one on field6
 *
 * @author alessia
 */
public class CreateOAIIndexAction extends AbstractOAIStoreAction {

	@Autowired
	private MongoPublisherStoreDAO mongoPublisherStoreDAO;

	@Override
	public void execute(final BlackboardServerHandler handler, final BlackboardJob job) throws Exception {
		String storeId = job.getParameters().get(OAIParameterNames.OAI_COLLECTON);
		String dbName = job.getParameters().get(OAIParameterNames.OAI_DB);
		// Examples: field1,field2 -- one compound index on the given two fields
		// field1,field2;field3,field4 -- two compound indices: one on field1 and field2, the other on field3 and field4
		String fieldNames = job.getParameters().get(OAIParameterNames.OAI_INDEXES);
		if (StringUtils.isBlank(dbName) || StringUtils.isBlank(storeId) || StringUtils.isBlank(fieldNames))
			throw new IllegalArgumentException(String.format(
					"Job parameters %s, %s and %s are mandatory", OAIParameterNames.OAI_DB, OAIParameterNames.OAI_COLLECTON, OAIParameterNames.OAI_INDEXES));
		else {
			MongoPublisherStore store = this.mongoPublisherStoreDAO.getStore(storeId, dbName);
			if (store != null) {
				String[] indexFieldList = fieldNames.replaceAll(" ", "").split(";");
				for (String idx : indexFieldList) {
					String[] fields = idx.split(",");
					store.createCompoundIndex(Arrays.asList(fields));
				}
				handler.done(job);
			} else throw new OaiPublisherRuntimeException("store " + storeId + " does not exist on db " + dbName + ": can't create compound indices");
		}
	}

	public MongoPublisherStoreDAO getMongoPublisherStoreDAO() {
		return this.mongoPublisherStoreDAO;
	}

	public void setMongoPublisherStoreDAO(final MongoPublisherStoreDAO mongoPublisherStoreDAO) {
		this.mongoPublisherStoreDAO = mongoPublisherStoreDAO;
	}

}
