package eu.dnetlib.organizations.importer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import eu.dnetlib.organizations.utils.DatabaseUtils;

@Component
public class ImportExecutor {

	@Autowired
	private DatabaseUtils databaseUtils;

	private final ImportExecution lastImportExecution = new ImportExecution();

	public ImportExecution getLastImportExecution() {
		return lastImportExecution;
	}

	public ImportExecution startImport(final String caller) {
		synchronized (lastImportExecution) {
			if (lastImportExecution.getStatus() != ImportStatus.RUNNING) {
				lastImportExecution.startNew("Importing dedup events - request from " + caller);
				new Thread(() -> {
					try {
						databaseUtils.importDedupEvents();
						lastImportExecution.complete();
					} catch (final Throwable e) {
						lastImportExecution.fail(e);
					}
				}).start();
			} else {
				final long now = System.currentTimeMillis();
				return new ImportExecution(null, now, now, ImportStatus.NOT_LAUNCHED, "An other import is running");
			}

		}
		return lastImportExecution;
	}
}
