package dev.peerat.backend.routes;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Test;

import dev.peerat.framework.RequestType;

public class StateTestCase{
	
	@Test
	void main() throws Exception{
		String host = "127.0.0.1";
		int port = 80;
		
		File dir = new File("./route-test/");
		for(File cases : dir.listFiles()){
			if(!cases.isDirectory()) continue;
			List<File> responses = new ArrayList<>();
			File dbsetup = null;
			for(File file : cases.listFiles()){
				if(file.getName().endsWith(".class")) dbsetup = file; else responses.add(file);
			}
//			Class<?> clazz = new URLClassLoader(new URL[]{cases.toURI().toURL()}).loadClass(dbsetup.getAbsolutePath().substring(cases.getAbsolutePath().length()+1).replace("/", ".").replace("\\", ".").replace(".class", ""));
			//setup database with clazz
			for(File file : responses){
				StateCase state = new StateCase(file);
				state.execute(host, port);
			}
		}
	}
	
	public static class StateCase{
		
		private String path;
		private RequestType type;
		private List<String> headers;
		private String payload;
		
		private int responseCode;
		private List<String> responseHeaders;
		private String responsePayload;
		
		public StateCase(File file) throws Exception{
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line;
			String payloadBuffer;
			this.headers = new ArrayList<>();
			this.responseHeaders = new ArrayList<>();
			
			this.path = reader.readLine();
			this.type = RequestType.valueOf(reader.readLine());
			
			while(((line = reader.readLine() )!= null) && (!line.isEmpty())) headers.add(line);
			
			payloadBuffer = "";
			while(((line = reader.readLine() )!= null) && (!line.isEmpty())) payloadBuffer+=line;
			this.payload = payloadBuffer;
			
			this.responseCode = Integer.parseInt(reader.readLine());
			while(((line = reader.readLine() )!= null) && (!line.isEmpty())) responseHeaders.add(line);
			
			payloadBuffer = "";
			while(((line = reader.readLine() )!= null) && (!line.isEmpty())) payloadBuffer+=line;
			this.responsePayload = payloadBuffer;
		}
		
		public void execute(String host, int port) throws Exception{
			Socket socket = new Socket(host, port);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			writer.write(this.type.toString()+" "+path+" HTTP/1.1\n");
			for(String header : headers) writer.write(header+"\n");
			writer.write("\n");
			if(payload != null) writer.write(payload+"\n");
			writer.flush();
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String line;
			while((line = reader.readLine()) != null) System.out.println(line);

			socket.close();
		}
	}
		
}
