package projectzombie.worker;

import java.util.Random;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

import gl_engine.vec.Vec2i;
import projectzombie.world.chunk.Chunk;
import projectzombie.world.layer.Layer;
import projectzombie.world.layer.layergen.LayerGen;

public class WorkerChunks extends Thread
{
	private boolean running = false;
	private Vector<WorkerChunkTask> chunks_in = new Vector<WorkerChunkTask>();
	private AtomicReference<Vector<Chunk>> chunks_out = new AtomicReference<Vector<Chunk>>();
	
	public void generateChunk(LayerGen layergen, Layer layer, Chunk chunk, Random rand, Vec2i pos) {
		chunks_in.add(new WorkerChunkTask(layergen, layer, chunk, rand, pos));
	}
	
	public Vector<Chunk> getChunks() {
		return chunks_out.getAndSet(new Vector<Chunk>());
	}
	
	public boolean hasChunk(Vec2i cpos)
	{
		boolean has[] = {false};
		
		chunks_in.forEach(c -> {
			if(c.pos.equal(cpos)) {
				has[0] = true;
			}
		});
		
		return has[0];
	}
	
	public WorkerChunks() {
		chunks_out.set(new Vector<Chunk>());
	}
	
	@Override
	public void run()
	{
		running = true;
		
		try
		{
			while(running)
			{
				if(chunks_in.size() == 0) {
					Thread.sleep(1);
					continue;
				}
				
				WorkerChunkTask ct = chunks_in.remove(0);
				
				Chunk chunk = ct.chunk;
				LayerGen layergen = ct.layergen;
				Layer layer = ct.layer;
				Random rand = ct.rand;
				Vec2i pos = ct.pos;
				
				layergen.generateChunk(chunk, layer, rand, pos);
				
				chunks_out.get().add(chunk);
			}
		}
		
		catch(InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void kill() {
		running = false;
	}
}
