package com.local;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.util.Properties;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

class TimeTest {

	private static final String JDBC_URL = "jdbc:mariadb://localhost:3306/mydb?user=user&password=password&createDatabaseIfNotExist=true";

	@BeforeAll
	static void setUp() throws Exception {
		final String queryDrop = "DROP TABLE IF EXISTS test_time";
		final String queryCreate = "CREATE TABLE test_time (   time_id INTEGER AUTO_INCREMENT PRIMARY KEY,   column_time TIME NOT NULL DEFAULT '00:00:00')";
		final String queryInsert1 = "INSERT INTO test_time values (1, '00:00:00')";
		final String queryInsert2 = "INSERT INTO test_time values (2, '01:00:00')";

		try (Connection con = DriverManager.getConnection(JDBC_URL)) {
			final Statement initStmt = con.createStatement();
			initStmt.execute(queryDrop);
			initStmt.execute(queryCreate);
			initStmt.execute(queryInsert1);
			initStmt.execute(queryInsert2);
		}
	}

	@ParameterizedTest
	@ValueSource(booleans = { true, false })
	void testWithTimeToZero(boolean useServerPrepStmts) throws SQLException {
		final Time expected = Time.valueOf("00:00:00");

		final Properties props = new Properties();
		props.put("useServerPrepStmts", useServerPrepStmts);

		try (Connection con = DriverManager.getConnection(JDBC_URL, props)) {
			final PreparedStatement stmt = con
					.prepareStatement("SELECT time_id, column_time FROM test_time WHERE time_id = ?");
			stmt.setInt(1, 1);

			final ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				Assertions.assertEquals(expected, rs.getTime(2));
			}
		}
	}

	@ParameterizedTest
	@ValueSource(booleans = { true, false })
	void testWithTimeDifferentFromZero(boolean useServerPrepStmts) throws SQLException {
		final Time expected = Time.valueOf("01:00:00");

		final Properties props = new Properties();
		props.put("useServerPrepStmts", useServerPrepStmts);

		try (Connection con = DriverManager.getConnection(JDBC_URL, props)) {
			final PreparedStatement stmt = con
					.prepareStatement("SELECT time_id, column_time FROM test_time WHERE time_id = ?");
			stmt.setInt(1, 2);

			final ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				Assertions.assertEquals(expected, rs.getTime(2));
			}
		}
	}
}
