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 Class DeleteIndexAction.
 */
public class DeleteIndexAction extends AbstractIndexAction implements BlackboardServerAction<IndexAction> {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(DeleteIndexAction.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("some Blackboard parameter is missing in DELETE message");
		MetadataReference mdRef = getMetadataReference(dsId);
		final String backendId = getBackend(job);
		if (backendId == null) throw new IndexServiceException("No backend identifier information in CREATE message");
		IndexCollection indexCollection = indexServerDAOMap.getIndexServerDAO(backendId).getIndexCollection(mdRef);
		if (indexCollection.deleteIndex(dsId) == false)
			throw new IndexServiceException("Error to delete collection the index response for the delete action is not OK");
		if (indexCollection.commit() == false)
			throw new IndexServiceException("Error to delete collection the index response for the delete action is not OK");
		if (!serviceTools.deleteIndexDS(dsId)) {
			log.warn("couldn't delete IndexDS: " + dsId);
		}
		log.info("\n\nDELETE report:" + "\n- dsId: " + dsId);
		indexCollection.shutdown();
		handler.done(job);
	}

}
