package com.github.ledoyen.winter.stepdef;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.inject.Provider;

import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;

import com.github.ledoyen.automocker.extension.sql.Connections;
import com.github.ledoyen.automocker.extension.sql.DataSources;
import com.github.ledoyen.automocker.extension.sql.DatasourceLocator;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;

import cucumber.api.DataTable;
import cucumber.api.java.After;
import cucumber.api.java.en.Given;

public class SqlStepDefs {

	@Autowired
	private Provider<DatasourceLocator> datasourceLocator;

	private final ListMultimap<String, String> tablesToClean = ArrayListMultimap.create();

	@Given("^an SQL table (\\S+) containing$")
	public void a_call_on_service_method_is_made(String tableName, DataTable data) throws Exception {
		DataSources.populateTable(datasourceLocator.get()
				.getDataSource(), tableName, data.topCells(), data.cells(1));
		tablesToClean.put(datasourceLocator.get()
				.getName(), tableName);
	}

	@After
	public void afterScenario() {
		tablesToClean.asMap()
				.forEach((dsName, names) -> DataSources.doInConnection(datasourceLocator.get()
						.getDataSource(dsName), c -> {
							// TODO fix this, not working
							List<String> copy = Lists.newArrayList(names);
							Collections.sort(copy, Comparator.reverseOrder());
							names.forEach(name -> Connections.truncate(c, name));
						}));
		tablesToClean.clear();
	}
}

@@ -60,73 +60,25 @@
 til.
-Collections;%0D%0Aimport java.util.Comparator;%0D%0Aimport java.util.List
+stream.Collectors
 ;%0D%0A%0D
@@ -126,31 +126,53 @@
 org.
-assertj.core.util.Lists
+slf4j.Logger;%0D%0Aimport org.slf4j.LoggerFactory
 ;%0D%0Ai
@@ -673,16 +673,101 @@
 fs %7B%0D%0A%0D%0A
+%09private static final Logger LOGGER = LoggerFactory.getLogger(SqlStepDefs.class);%0D%0A%0D%0A
 %09@Autowi
@@ -1465,90 +1465,126 @@
 %09%09%09%09
-// TODO fix this, not working%0D%0A%09%09%09%09%09%09%09List%3CString%3E copy = Lists.newArrayList(
+Connections.execute(c, %22SET REFERENTIAL_INTEGRITY FALSE%22);%0D%0A%09%09%09%09%09%09%09names.forEach(name -%3E Connections.truncate(c, 
 name
-s
+)
 );%0D%0A
@@ -1596,18 +1596,18 @@
 %09%09Co
-ll
+nn
 ections.
 sort
@@ -1606,106 +1606,179 @@
 ons.
-sort(copy, Comparator.reverseOrder());%0D%0A%09%09%09%09%09%09%09names.forEach(name -%3E Connections.truncate(c, name)
+execute(c, %22SET REFERENTIAL_INTEGRITY TRUE%22);%0D%0A%09%09%09%09%09%09%09LOGGER.info(%22%5B%22 + dsName + %22%5D Tables (%22 + names.stream()%0D%0A%09%09%09%09%09%09%09%09%09.collect(Collectors.joining(%22, %22)) + %22) truncated%22
 );%0D%0A

fix truncate operation in SQL @After hook