package eu.dnetlib.functionality.index.action;

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

import eu.dnetlib.data.provision.index.rmi.IndexServiceException;
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
import eu.dnetlib.functionality.index.IndexCollection;
import eu.dnetlib.functionality.index.IndexServerDAOMap;
import eu.dnetlib.functionality.index.utils.MetadataReference;

/**
 * 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 eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction#execute(eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler,
	 *      eu.dnetlib.enabling.tools.blackboard.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);
	}

}
