package ca.uhn.fhir.jpa.migrate.taskdef;

import ca.uhn.fhir.jpa.migrate.DriverTypeEnum;
import ca.uhn.fhir.jpa.migrate.tasks.api.ISchemaInitializationProvider;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class InitializeSchemaTask extends BaseTask<InitializeSchemaTask> {
	private static final Logger ourLog = LoggerFactory.getLogger(InitializeSchemaTask.class);
	private final ISchemaInitializationProvider mySchemaInitializationProvider;

	public InitializeSchemaTask(String theRelease, String theVersion, ISchemaInitializationProvider theSchemaInitializationProvider) {
		super(theRelease, theVersion);
		mySchemaInitializationProvider = theSchemaInitializationProvider;
	}

	@Override
	public void validate() {
		// nothing
	}

	@Override
	public void execute() throws SQLException {
		DriverTypeEnum driverType = getDriverType();

		logInfo(ourLog, "Initializing schema for {}", driverType);

		List<String> sqlStatements = mySchemaInitializationProvider.getSqlStatements(driverType);

		for (String nextSql : sqlStatements) {
			executeSql(null, nextSql);
		}
	}

	@Override
	public boolean equals(Object theO) {
		if (this == theO) return true;

		if (theO == null || getClass() != theO.getClass()) return false;

		InitializeSchemaTask that = (InitializeSchemaTask) theO;

		return new EqualsBuilder()
			.append(mySchemaInitializationProvider, that.mySchemaInitializationProvider)
			.isEquals();
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder(17, 37)
			.append(mySchemaInitializationProvider)
			.toHashCode();
	}
}

@@ -82,16 +82,58 @@
 peEnum;%0A
+import ca.uhn.fhir.jpa.migrate.JdbcUtils;%0A
 import c
@@ -446,16 +446,38 @@
 il.List;
+%0Aimport java.util.Set;
 %0A%0Apublic
@@ -1109,16 +1109,269 @@
 ype();%0A%0A
+%09%09Set%3CString%3E tableNames = JdbcUtils.getTableNames(getConnectionProperties());%0A%09%09if (tableNames.contains(%22HFJ_RESOURCE%22)) %7B%0A%09%09%09logInfo(ourLog, %22The table HFJ_RESOURCE already exists.  Skipping schema initialization for %7B%7D%22, driverType);%0A%09%09%09return;%0A%09%09%7D%0A%0A
 %09%09logInf

abort schema initialization if HFJ_RESOURCE table already exists