package be.jeffcheasey88.peeratcode.routes;

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

import org.json.simple.JSONObject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;

import be.jeffcheasey88.peeratcode.Main;
import be.jeffcheasey88.peeratcode.webclient.WebClient;

@TestInstance(Lifecycle.PER_CLASS)
public class ScoreTests {

	private Thread server;
	private WebClient client;
	
	@BeforeAll
	void init(){
		server = new Thread(new Runnable(){
			@Override
			public void run(){
				try {
					Main.main(null);
				} catch (Exception e) {
					e.printStackTrace();
				};
			}
		});
		server.start();
		client = new WebClient("localhost", 80);
	}
	
	@AfterAll
	void close(){
		server.interrupt();
	}
	
	@Test
	void testOnDeployed(){
		try{
			JSONObject group = new JSONObject();
			group.put("name", "GroupTest");
			group.put("chapter", 2);
			
			client.register("Test1", "Test2", "Test3@Test7.be", "Test4", "Test5", "Test6");
			client.assertResponseCode(200);
			
			client.route("/groupCreate", "POST", group.toJSONString());
			client.assertResponseCode(200);
			
			client.sendHeaders.add("content-type: ah;boundary=----WebKitFormBoundaryNUjiLBAMuX2dhxU7");
			client.route("/puzzleResponse/14", "POST", WebClient.buildMultiPartData("seven"));
			client.assertResponseCode(200);
			client.sendHeaders.clear();
			
			client.disconnect();
			
			client.auth("JeffCheasey88", "TheoPueDesPieds");
			client.route("/groupJoin", "POST", group.toJSONString());
			client.assertResponseCode(200);
			
			client.sendHeaders.add("content-type: ah;boundary=----WebKitFormBoundaryNUjiLBAMuX2dhxU7");
			client.route("/puzzleResponse/14", "POST", WebClient.buildMultiPartData("seven"));
			client.assertResponseCode(403);
			client.sendHeaders.clear();
		}catch(Exception e){
			e.printStackTrace();
			fail(e);
		}
	}
}
