package dev.peerat.backend.userstories;

import org.json.simple.JSONObject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;

import dev.peerat.backend.Main;
import dev.peerat.backend.WebClient;

@TestInstance(Lifecycle.PER_METHOD)
public class RegisterTests extends BaseUserStoriesTest{
	
	private Thread server;
	private WebClient client;
	
	@BeforeEach
	public void init() throws Exception{
		Class.forName("com.mysql.cj.jdbc.Driver");
		
		super.init();
		getRepository().init();
		getRepository().reset();
		
		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);
	}
	
	@AfterEach
	public void stop(){
		server.interrupt();
		getRepository().close();
	}
	
	@Test
	public void normalRegister() throws Exception{
		client.register("test", "test", "test@peerat.dev", "te", "st", "my desc");
		client.assertResponseCode(200);
	}
	
	@Test
	public void pseudoAlreadyUse() throws Exception{
		client.register("test", "test", "test@peerat.dev", "te", "st", "my desc");
		client.assertResponseCode(200);
		client.disconnect();
		client.register("test", "test", "test1@peerat.dev", "te", "st", "my desc");
		client.assertResponseCode(400);
	}
	
	@Test
	public void emailAlreadyUse() throws Exception{
		client.register("test", "test", "test@peerat.dev", "te", "st", "my desc");
		client.assertResponseCode(200);
		client.disconnect();
		client.register("test1", "test", "test@peerat.dev", "te", "st", "my desc");
		client.assertResponseCode(400);
	}
	
	@Test
	public void emptyField() throws Exception{
		client.register("","","",",","","");
		client.assertResponseCode(400);
	}
	
	@Test
	public void lostField() throws Exception{
		client.route("/register", "POST", new JSONObject().toJSONString());
		client.assertResponseCode(400);
	}
	
	@Test
	public void alreadyLoggedin() throws Exception{
		client.register("test", "test", "test@peerat.dev", "te", "st", "my desc");
		client.assertResponseCode(200);
		client.register("test1", "test", "test@peerat.dev", "te", "st", "my desc");
		client.assertResponseCode(403);
	}
}
