package net.bakingpowder.jspl.tcprelay.buffering;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.LinkedList;

/**
 * @author Tomoo D. Mizukami/JAIST/Softbank Publishing Inc.
 * 
 * This class is multi-thread class for buffer-interchange-function.
 */
public class Input2Output implements Runnable {
	private InputStream in = null;
	private OutputStream out = null;
	private ConnectControl cc = null;
	private byte buffer[] = null;
	static int BUFFER_SIZE = 4096;
	private static int TIME_INTERVAL = 5;
	private boolean stopper = false;
	
	public synchronized void stopd(){
		this.stopper = true;
	}
	
	/**
	 * @param in
	 *            InputStream
	 * @param out
	 *            OutputStream
	 * @param cm
	 *            ConnectControl
	 */
	public Input2Output(InputStream in, OutputStream out, ConnectControl cc) {
		this.in = in;
		this.out = out;
		this.cc = cc;
		buffer = new byte[BUFFER_SIZE];

		t = new Thread(this);
		t.start();
	}
	private Thread t;

	public void run() {
		try {
		    
			int bytesRead = 0;
			BoundedQueue bq = new BoundedQueue(100);
			
			SrcRead sr = new SrcRead(in,bq);

			
			LOOP1 : while (!this.stopper) {
			    if (!bq.isEmpty()){
				    Buf buf = (Buf)bq.dequeue();
				
				    if (buf.length == -1) break;	    
					out.write(buf.value, 0, buf.length);
			    }
			    			    
			    
			}

			sr.stopd();		
			
		} catch (IOException e) {
			//ignore
		}
		
		cc.ThreadArrivedEnd(this);
	}
	
	public LinkedList ls;
}

class Buf {
    int length;
    byte[] value;
    
    Buf(int size){
        value = new byte[size];
    }
}

