/*
 * TestPolymakeServer.java
 *
 * Created on November 2, 2005, 3:07 PM
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package de.tuberlin.polymake.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.Channels;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

import javax.swing.JTextArea;

/**
 *
 * @author thilosch
 */
public class SocketThread extends Thread{
    
    protected int port = -1;
	protected SocketChannel socketChannel;
	protected JTextArea receivedTextArea;
    
    /** Creates a new instance of TestPolymakeServer */
    public SocketThread(int port, JTextArea ta) {
    	super("SocketThread");
    	this.port = port;
    	receivedTextArea = ta;
    }
    
    public void run() {
    	try {
			ServerSocketChannel ssChannel = ServerSocketChannel.open();
			InetSocketAddress isa = new InetSocketAddress(InetAddress
					.getByName("localhost"), port);
			ssChannel.socket().bind(isa);
			ssChannel.configureBlocking(false);
			Selector selector = Selector.open();
			SelectionKey acceptKey = ssChannel.register(selector,
					SelectionKey.OP_ACCEPT);
			selector.select();
			socketChannel = ssChannel.accept();
			socketChannel.configureBlocking(false);
			acceptKey.cancel();
			SelectionKey readKey = socketChannel.register(selector,
					SelectionKey.OP_READ);
			BufferedReader clientReader = new BufferedReader(Channels
					.newReader(socketChannel, "ISO-8859-1"));
			while(true) {
				selector.select();
				Set selectedKeys = selector.selectedKeys();
				Iterator ki = selectedKeys.iterator();
				while(ki.hasNext()) {
					SelectionKey actKey = (SelectionKey)ki.next();
					ki.remove();
					if(actKey == readKey) {
						String line = new String();
						while((line = clientReader.readLine()) != null) {
							receivedTextArea.append("\n---------------------------------\n");
							receivedTextArea.append(line + "\n");
						}
					}
				}
			}
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace(System.err);
		}
    }
    
    public SocketChannel getSocketChannel() {
    	return socketChannel;
    }
}
