package eu.dnetlib.organizations.importer;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import eu.dnetlib.organizations.controller.OpenaireInternalApiController;

public class ImportExecution {

	private String id;
	private Long dateStart;
	private Long dateEnd;
	private ImportStatus status = ImportStatus.NOT_YET_STARTED;
	private String message;

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

	public ImportExecution() {}

	public ImportExecution(final String id, final Long dateStart, final Long dateEnd, final ImportStatus status, final String message) {
		this.id = id;
		this.dateStart = dateStart;
		this.dateEnd = dateEnd;
		this.status = status;
		this.message = message;
	}

	public String getId() {
		return id;
	}

	public void setId(final String id) {
		this.id = id;
	}

	public Long getDateStart() {
		return dateStart;
	}

	public void setDateStart(final Long dateStart) {
		this.dateStart = dateStart;
	}

	public Long getDateEnd() {
		return dateEnd;
	}

	public void setDateEnd(final Long dateEnd) {
		this.dateEnd = dateEnd;
	}

	public ImportStatus getStatus() {
		return status;
	}

	public void setStatus(final ImportStatus status) {
		this.status = status;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(final String message) {
		this.message = message;
	}

	public void startNew(final String message) {
		setId("import-" + UUID.randomUUID());
		setDateStart(System.currentTimeMillis());
		setDateEnd(null);
		setStatus(ImportStatus.RUNNING);
		setMessage(message);
		log.info(message);
	}

	public void complete() {
		setDateEnd(System.currentTimeMillis());
		setStatus(ImportStatus.SUCCESS);

		final long millis = getDateEnd() - getDateStart();
		setMessage(String
			.format("Import of dedup events completed in %d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) -
				TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));

		log.info(getMessage());

	}

	public void fail(final Throwable e) {
		setDateEnd(new Date().getTime());
		setStatus(ImportStatus.FAILED);
		setMessage(e.getMessage());
		log.error("Error importing conflicts and duplicates", e);
	}

}
