import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientConnection implements Runnable {
    private ClientModel model;
    private Socket connection;
    private PrintWriter out;
    
    public ClientConnection(ClientModel model) throws IOException {
        this.model = model;
        this.connection = new Socket(ClientGui.CHAT_HOST, ClientGui.CHAT_PORT);
        this.out = new PrintWriter(this.connection.getOutputStream());

        // TODO: start thread to read input
    }
    
    public String send(String request) {
        // TODO: send message to out prefixed by unique ID, and wait for thread to get response with that ID
        return null;
    }
    
    public void run() {
        InputStream istream;
        try {
            istream = connection.getInputStream();
        } catch (IOException e) {
            System.err.println("client aborted in starting input");
            return;
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(istream));
        while (true) {
            String line;
            try {
                line = in.readLine();
            } catch (IOException e) {
                System.err.println("client aborted on reading input");
                break;
            }
            if (line == null) {
                System.out.printf("%s: end of transmission\n", model.getUserId());
                break;
            }
            
			String[] parts = line.trim().split("\\s+", 3);
			if (parts.length > 0) {
				processMessage(parts[0],
					parts.length > 1 ? parts[1] : "",
					parts.length > 2 ? parts[2] : "");
			}
        }

        try {
            connection.close();
        } catch (IOException e) { System.err.printf("%s: exception on close", model.getUserId()); }
        try { model.logOut(); } catch (ClientModel.ClientException e) { }
    }
    
    private void processMessage(String op, String arg0, String arg1) {
        // TODO handle message
    }
}
