package eu.dnetlib.data.objectstore.modular;

import eu.dnetlib.data.objectstore.rmi.ObjectStoreServiceException;
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * The Class CreateObjectStoreAction is responsible to execute the blacboard action of type CREATE.
 */
public class CreateObjectStoreAction extends AbstractObjectStoreAction {

	private static final Log log = LogFactory.getLog(CreateObjectStoreAction.class);

	/** The profile creator. */
	private ObjectStoreProfileCreator profileCreator;

	/**
	 * Gets the profile creator.
	 *
	 * @return the profile creator
	 */
	public ObjectStoreProfileCreator getProfileCreator() {
		return profileCreator;
	}

	/**
	 * Sets the profile creator.
	 *
	 * @param profileCreator the new profile creator
	 */
	public void setProfileCreator(final ObjectStoreProfileCreator profileCreator) {
		this.profileCreator = profileCreator;
	}

	@Override
	protected void executeAsync(final BlackboardServerHandler handler, final BlackboardJob job) {
		try {
			final String interpretation = job.getParameters().get("interpretation");
//			final String basePath = job.getParameters().get("basePath");
//			if (StringUtils.isBlank(basePath)) {
//				throw new ObjectStoreServiceException("missing basePath param");
//			}

			final String objID = profileCreator.registerProfile(interpretation);
			try {
				getDao().createObjectStore(objID, interpretation, null);
			} catch (Throwable e) {
				log.warn("cannot created objectStore, deleting profile");
				profileCreator.deleteProfile(objID);
				throw new ObjectStoreServiceException(e);
			}
			job.getParameters().put("objectStoreId", objID);
			completeWithSuccess(handler, job);
		} catch (Exception e) {
			completeWithFail(handler, job, e);
		}

	}
}
