package com.github.ledoyen.winter.stepdef;

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

import javax.inject.Provider;
import javax.sql.DataSource;

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<DataSource, 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()
				.getDataSource(), tableName);
	}

	@After
	public void afterScenario() {
		tablesToClean.asMap()
				.forEach((ds, names) -> DataSources.doInConnection(ds, 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();
	}
}

@@ -160,38 +160,8 @@
 er;%0D
-%0Aimport javax.sql.DataSource;%0D
 %0A%0D%0Ai
@@ -799,26 +799,22 @@
 ultimap%3C
-DataSource
+String
 , String
@@ -1176,33 +1176,27 @@
 ()%0D%0A%09%09%09%09.get
-DataSourc
+Nam
 e(), tableNa
@@ -1289,16 +1289,20 @@
 Each((ds
+Name
 , names)
@@ -1333,17 +1333,68 @@
 ection(d
-s
+atasourceLocator.get()%0D%0A%09%09%09%09%09%09.getDataSource(dsName)
 , c -%3E %7B
@@ -1395,16 +1395,18 @@
 c -%3E %7B%0D%0A
+%09%09
 %09%09%09%09%09// 
@@ -1438,16 +1438,18 @@
 g%0D%0A%09%09%09%09%09
+%09%09
 List%3CStr
@@ -1484,24 +1484,26 @@
 st(names);%0D%0A
+%09%09
 %09%09%09%09%09Collect
@@ -1552,16 +1552,18 @@
 ;%0D%0A%09%09%09%09%09
+%09%09
 names.fo
@@ -1605,24 +1605,26 @@
 c, name));%0D%0A
+%09%09
 %09%09%09%09%7D));%0D%0A%09%09

remove DataSource reference from SQL step definitions