package zh2015.IP_chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import zh2015.IP_chat.GUI.Who;

public class Network extends Thread {
	
	protected ServerSocket serverSocket;
	protected Socket clientSocket = null;
	protected GUI gui;
	protected String stringToSend = null;
	protected boolean connectionChanged = false;
	
	public Network(GUI gui) {
		this.gui = gui;
		
		(new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					serverSocket = new ServerSocket(Integer.parseInt(gui.lbMyPort.getText()));
				} catch (NumberFormatException | IOException e) {
					gui.addToList(e.getMessage(), Who.Error);
				}
			}

		})).start();
	}
	
	public synchronized void BuildConnection() {
		(new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					clientSocket = new Socket("localhost", Integer.parseInt(gui.txtPort.getText()));
				} catch (NumberFormatException | IOException e) {
					gui.addToList(e.getMessage(), Who.Error);
				}
			}
		})).start();
		
		connectionChanged = true;
		this.notifyAll();
	}
	
	public synchronized void StopConnection() {
		clientSocket = null;
		connectionChanged = true;
		this.notifyAll();
	}
	
	public synchronized void Send() {
		stringToSend = gui.txtNewMessage.getText();
		this.notifyAll();
	}
	
	@Override
	public synchronized void run() {
		try {
			while (!this.isInterrupted()) {
				while (clientSocket == null)
					this.wait();
				
				try {
					
					BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
					PrintWriter output = new PrintWriter(clientSocket.getOutputStream());
					Input input = new Input(this, inputReader);
					input.start();
					
					connectionChanged = false;
					this.wait();
					while (!connectionChanged) {
						if (stringToSend != null) {
							output.println(stringToSend);
							gui.addToList(stringToSend, Who.Me);
							stringToSend = null;
						}
						if (input.recieved != null) {
							gui.addToList(input.recieved, Who.Partner);
							input.recieved = null;
						}
						this.wait();
					}
					
				} catch (IOException e) {
					clientSocket = null;
					gui.addToList(e.getMessage(), Who.Error);
				}
			}
		} catch (InterruptedException e) {
			gui.addToList(e.getMessage(), Who.Error);
		}
	}
}
