// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package jcademo.raoutbound.permtcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

public class TCPMultiPlexer {
	// singleton
	private static TCPMultiPlexer instance = new TCPMultiPlexer();
	public static TCPMultiPlexer getInstance() {
		return instance;
	}
	// data
	private Socket s;
	private PrintStream ps;
	private BufferedReader br;
	private Map<String, BlockingQueue<String>> qmap = new HashMap<String, BlockingQueue<String>>();
	// connect
	public void connect(String host, int port) throws IOException {
		s = new Socket(host, port);
		ps = new PrintStream(s.getOutputStream(), true, "UTF-8");
		br = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
	}
	// register receive queue
	public void register(String id, BlockingQueue<String> q) {
		synchronized(qmap) {
			qmap.put(id, q);
		}
	}
	// send
	public void send(String id, String line) throws InterruptedException {
		synchronized(ps) {
			ps.println(id);
			ps.println(line);
			ps.flush();
		}
	}
	// deregister receive queue
	public void deregister(String id) {
		synchronized(qmap) {
			qmap.remove(id);
		}
	}
	// close
	public void close() throws IOException {
		br.close();
		ps.close();
		s.close();
	}
	// receive loop that put responses in correct queue
	public void receive() throws IOException, InterruptedException {
		while(true) {
			String id = br.readLine();
			if(id == null) break;
			String line = br.readLine();
			if(line == null) break;
			qmap.get(id).put(line);
		}
	}
}
