package projectzombie.mainloop;

import java.util.ArrayList;

import mainloop.task.IMainloopTask;

class AsyncTask
{
	int i, max;
	MainloopEnd end;
	MainloopIterator iterator;
	
	AsyncTask(int min, int max, MainloopIterator iterator, MainloopEnd end) {
		this.i = min;
		this.max = max;
		this.end = end;
		this.iterator = iterator;
	}
	
	void update() {
		long start = System.currentTimeMillis();
		
		while(i < max && System.currentTimeMillis() - start < 2) {
			iterator.iterate(i);
			i += 1;
		}
		
		if(i == max) {
			end.end();
			i += 1;
		}
	}
	
	boolean done() {
		return i > max;
	}
}

public class MainloopHelpers implements IMainloopTask
{
	private static ArrayList<AsyncTask> tasks = new ArrayList<AsyncTask>();
	
	public static void loopAsync(int min, int max, MainloopIterator iterator, MainloopEnd end) {
		tasks.add(new AsyncTask(min, max, iterator, end));
	}
	
	public static void loopSync(int min, int max, MainloopIterator iterator, MainloopEnd end) {
		for(int i=min;i<max;i++) {
			iterator.iterate(i);
		}
		end.end();
	}

	@Override
	public boolean MainLoopDelay(long millis) {
		return millis > 10;
	}

	@Override
	public boolean MainLoopRepeat() {
		return true;
	}

	@Override
	public void MainLoopUpdate()
	{
		long start = System.currentTimeMillis();
		
		for(int i=0;i<tasks.size();i++) {
			AsyncTask t = tasks.get(i);
			if(t.done()) {
				tasks.remove(i);
				i -= 1;
				return;
			}
			t.update();
		}
		
		if(System.currentTimeMillis() > start + 5) {
			tasks.remove(0);
		}
	}
}
