package com.atomikos.examples.tomcat.jdbc;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.DockerComposeContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;


@Testcontainers
public class TomcatExampleIT {

	@Container
	public static DockerComposeContainer<?> docker = new DockerComposeContainer<>(new File("docker-compose.yml"))
			.withRemoveVolumes(true)
			.withExposedService("tomcat_1", 8080);

	static String address;

	@BeforeAll
	static void beforeAll() {
		docker.start();
		address = "http://" + docker.getServiceHost("tomcat_1", 8080) + ":"+ docker.getServicePort("tomcat_1", 8080)+"/examples-tomcat";
	}

	@AfterAll
	static void afterAll() {
		docker.stop();
	}

//	@Test
//	void balance() throws Exception {
//		assertEquals("balance is 10000 for account 1", performGetOnUrl("/jdbc"));
//	}
	
	@Test
	void withdraw() throws Exception {
		assertEquals("balance is 9950 for account 2", performGetOnUrl("/jdbc?account=2&operation=withdraw&amount=50"));
	}
	
	@Test
	void sendJms() throws Exception {
		assertEquals("Message publised on queue: jms/queue/MyQueue", performGetOnUrl("/jms"));
	}
	
	private String performGetOnUrl(String path) throws IOException, ProtocolException {
		URL url = new URL(address + path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");

		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		StringBuffer response = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			response.append(line);
		}
		reader.close();
		conn.disconnect();
		return response.toString();
	}
}
