package Loes_Aufg_9_3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

public class Loes_Aufg_9_3 
{
	String ip;
	int port;
	Socket server;
	OutputStream outToServer;
	InputStream inFromServer;

	public Loes_Aufg_9_3(String ip, int port)
	{
		this.ip = ip;
		this.port = port;
	}

	public void baueVerbindungAuf() throws UnknownHostException, IOException
	{
		this.server = new Socket(ip, port);

		System.out.println("Client verbunden mit: " + this.server.getInetAddress() + ":" + this.server.getPort());

		this.outToServer = this.server.getOutputStream();
		this.inFromServer = this.server.getInputStream();
	}

	public Befehl sendeBefehl(Befehl befehl) throws IOException
	{
		byte[] bytes = new byte[6];
		Befehl antwort = new Befehl();

		outToServer.write(befehl.baueBefehlString());

		int read = inFromServer.read(bytes, 0, 6);
		if(read == -1)
		{
			schliesseVerbindung();
			return antwort;
		}
		antwort.anfrage = new String(bytes, 0, 3, Charset.forName("ASCII"));
		String antwortAnhangLaenge = new String(bytes, 3, 3, Charset.forName("ASCII"));

		int anhangLaenge = Integer.parseInt(antwortAnhangLaenge);
		if(anhangLaenge > 0)
		{
			bytes = new byte[anhangLaenge];
			inFromServer.read(bytes, 0, anhangLaenge);
			antwort.anhang = new String(bytes, 0, anhangLaenge, Charset.forName("UTF-8"));
		}
		return antwort;
	}

	public void schliesseVerbindung() throws IOException
	{
		outToServer.close();
		inFromServer.close();
		server.close();
	}

	public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException
	{
		String ip =  "angewnwt.hof-university.de";
		int port  =  4439;
		
		Loes_Aufg_9_3 client = new Loes_Aufg_9_3(ip, port);

		client.baueVerbindungAuf();

		// Alle Matrikelnummern durchprobieren
		for(int matNr = 10000; matNr < 30000; matNr++ ) {
			
			// Finde Name zu Matrikelnummer 
			Befehl befehl = new Befehl(); 
			befehl.anfrage = "STU";
			befehl.anhang = Integer.toString(matNr);
			Befehl antwort = client.sendeBefehl(befehl);
			if(antwort.anhang.length() > 0) {
				String teile[] = antwort.anhang.split(";");

				int matrikelNummer = Integer.parseInt(teile[0]);
				String name = teile[1];
				
				System.out.println("Gueltige Matrikelnummer: "+ matrikelNummer + ": " + name);
			}
		}
		client.schliesseVerbindung();
	}
}
