package eu.dnetlib.index.action;

import eu.dnetlib.utils.MetadataReference;
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
import eu.dnetlib.index.IndexCollection;
import eu.dnetlib.index.IndexServerDAOMap;
import eu.dnetlib.rmi.provision.IndexServiceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * The Delete by Query Action. It expects the query to be in Solr/Lucene format.
 */
public class DeleteByQueryAction extends AbstractIndexAction implements BlackboardServerAction<IndexAction> {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(DeleteByQueryAction.class);

	/**
	 * The index server dao map.
	 */
	@Autowired
	private IndexServerDAOMap indexServerDAOMap;

	/**
	 * {@inheritDoc}
	 *
	 * @see BlackboardServerAction#execute(BlackboardServerHandler,
	 * BlackboardJob)
	 */
	@Override
	public void execute(final BlackboardServerHandler handler, final BlackboardJob job) throws IndexServiceException {
		final String dsId = getIndexDSId(job);
		if (dsId == null) throw new IndexServiceException("dsId Blackboard parameter is missing in DELETE BY QUERY message");
		final MetadataReference mdRef = getMetadataReference(dsId);
		final String backendId = getBackend(job);
		if (backendId == null) throw new IndexServiceException("No backend identifier information in DELETE BY QUERY message");
		final IndexCollection indexCollection = indexServerDAOMap.getIndexServerDAO(backendId).getIndexCollection(mdRef);

		// TODO The query should be passed in CQL format
		final String query = getQuery(job);

		log.info("DELETE BY QUERY: '" + query + "' on index '" + mdRef + "'");

		// here we pass the query as it is, no dsId.
		if (indexCollection.deleteByQuery(query, null) == false)
			throw new IndexServiceException(String.format("Error to delete on index '%s', query '%s'", mdRef, query));
		if (indexCollection.commit() == false)
			throw new IndexServiceException(String.format("Error to commit on index '%s'", mdRef));

		log.info("DELETE BY QUERY done");
		indexCollection.shutdown();
		handler.done(job);
	}

}
