package projectzombie.worker;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import java.util.zip.GZIPOutputStream;

import bdf.types.BdfReader;
import projectzombie.Main;

public class WorkerFile extends Thread
{
	private static Vector<WorkerFileTask> tasks = new Vector<WorkerFileTask>();
	
	public static void addTask(String path, BdfReader reader) {
		tasks.add(new WorkerFileTask(path, reader));
	}
	
	private synchronized WorkerFileTask getNextIfAvailable()
	{
		if(tasks.size() == 0) {
			return null;
		} else {
			return tasks.remove(0);
		}
	}
	
	@Override
	public void run()
	{
		try
		{
			while(Main.running)
			{
				WorkerFileTask task = getNextIfAvailable();
				
				if(task == null) {
					Thread.sleep(10);
					continue;
				}
				
				try
				{
					OutputStream out = new FileOutputStream(task.path);
					out = new GZIPOutputStream(out);
					
					task.reader.serialize().writeToStream(out);
					
					out.close();
				}
				
				catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		catch(InterruptedException e) {
			e.printStackTrace();
		}
	}
}
