package org.rki.readclassifier;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Writer extends Thread {
	private BufferedWriter out1w;
	private BufferedWriter out2w;
        public BlockingQueue<ReadPair> outReads;
//	public LinkedList<ReadPair> outReads = new LinkedList<ReadPair>();
	
	public Writer(OutputStream out1, OutputStream out2, int numReads) {
                outReads = new LinkedBlockingQueue<ReadPair>(numReads);
		out1w = new BufferedWriter(new OutputStreamWriter(out1));
		out2w = out2==null?null:new BufferedWriter(new OutputStreamWriter(out2));
	}
	
        public void run() {
            while(true) {
                try {
                    ReadPair reads = outReads.take();
                    if(reads.read1 == null)
                        break;
                    if(reads.read1.invalid && reads.read2.invalid)
                    	continue;
                    if(Classifier.useCutoff == Classifier.Cutoff.HIGHER && reads.read1.score < Classifier.cutoffHigher)
                    	continue;
                    else if(Classifier.useCutoff == Classifier.Cutoff.LOWER && reads.read1.score > Classifier.cutoffLower)
                    	continue;
                    out1w.write(reads.read1.toString(true));
                    if(out2w != null && reads.read2 != null)
                        out2w.write(reads.read2.toString(true));
                } catch(Exception e) {
                }
            }
            try {
                out1w.close();
                if(out2w != null)
                    out2w.close();
            } catch(Exception e) {}
        }
        
	public void write() {
		try {
			for(ReadPair reads : outReads) {
				out1w.write(reads.read1.toString(true));
				if(out2w != null && reads.read2 != null) {
					out2w.write(reads.read2.toString(true));
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		outReads.clear();
	}
	
	public void close() {
		write();
		try {
			out1w.close();
			if(out2w != null)
				out2w.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
