package learner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class SutWrapper {
	private Socket sock;
	private PrintWriter sockout;
	private BufferedReader sockin;
	private List<String> inputs;

	public SutWrapper() {
		try {
			sock = new Socket("localhost", 7892);
			sock.setTcpNoDelay(true);  // remove unnecesarry delay in socket communication!
			sockout = new PrintWriter(sock.getOutputStream(), true);
			sockin = new BufferedReader(new InputStreamReader(sock.getInputStream()));
			inputs = new ArrayList<String>();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String sendBasicInput(String input) {
		try {	
			System.out.println("SutWrapper sending: " + input);

			// Send input to SUT
			sockout.println(input);
			sockout.flush();

			// Receive output from SUT
			String concreteOutput = sockin.readLine();		
			return concreteOutput;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public String sendInput(String input) {
		try {	
			System.out.println("SutWrapper sending: " + input);

			// Send input to SUT
			sockout.println(input);
			sockout.flush();
			inputs.add(input);

			// Receive output from SUT
			String concreteOutput = sockin.readLine();
			while(concreteOutput == "error"){
				System.out.println("SutWrapper receiving: " + concreteOutput);
				sendBasicReset();
				for(String i : inputs){
					concreteOutput = sendBasicInput(i);
					if(concreteOutput=="error")
						break;
				}
			}
			
			return concreteOutput;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void sendBasicReset() {
		System.out.println("SutWrapper sending: reset");
		sockout.println("reset");
		sockout.flush();
	}

	public void sendReset() {
		sendBasicReset();
		inputs = new ArrayList<String>();
	}
	
	public void sendConnect() {
		System.out.println("SutWrapper sending: connect");
		sockout.println("connect");
		sockout.flush();
	}
	
	public void close() {
		try {
			sockin.close();
			sockout.close();
			sock.close();
		} catch (IOException ex) {
			
		}
	}
}
