package primer12;

import java.io.*;
import java.util.*;

public class PooledWeblog {

	private BufferedReader in;
	private BufferedWriter out;
	private int numberOfThreads;
	private List<String> entries = Collections.synchronizedList(new LinkedList<String>());
	private boolean finished = false;

	public PooledWeblog(InputStream in, OutputStream out, int numberOfThreads) {
		this.in = new BufferedReader(new InputStreamReader(in));
		this.out = new BufferedWriter(new OutputStreamWriter(out));
		this.numberOfThreads = numberOfThreads;
	}

	public boolean isFinished() {
		return finished;
	}

	public int getNumberOfThreads() {
		return numberOfThreads;
	}

	public void processLogFile() {
		for (int i = 0; i < numberOfThreads; i++) {
			Thread t = new Thread(new LookupThread(entries, this));
			t.start();
		}

		try {

			String entry = in.readLine();
			while (entry != null) {
				// System.out.println("*"+entry+"*");
				if (entries.size() > numberOfThreads) {
					try {
						Thread.sleep((long) (1000.0 / numberOfThreads));
					} catch (InterruptedException ex) {
					}
					continue;
				}

				synchronized (entries) {
					entries.add(0, entry);
					entries.notifyAll();
				}

				entry = in.readLine();
				Thread.yield();
			}
			finished = true;
			synchronized (entries) {
				entries.notifyAll();
			}

		} catch (IOException ex) {
		}
	}

	public void log(String entry) throws IOException {
		out.write(entry + System.getProperty("line.separator", "\r\n"));
		out.flush();
	}

	public static void main(String[] args) {

		try {
			PooledWeblog tw = new PooledWeblog(new FileInputStream(args[0]), System.out, 6);
			tw.processLogFile();
		} catch (FileNotFoundException ex) {
			System.err.println("Usage: java PooledWeblog logfile_name");
		} catch (ArrayIndexOutOfBoundsException ex) {
			System.err.println("Usage: java PooledWeblog logfile_name");
		}
	} // end main

}
