package projectzombie.mainloop;

import mainloop.event.IMainloopEvent;
import mainloop.task.IMainloopTask;
import projectzombie.Main;

public class MainloopEventHandler implements IMainloopEvent, IMainloopTask
{
	public static final MainloopEventHandler MAINLOOP_EVENT_HANDLER = new MainloopEventHandler();
	
	private long autosave_interval = 0;
	private long max_mspf = 1;
	public long mspf = max_mspf;

	@Override
	public void onClose()
	{
		// Close OpenAL
		System.out.println("Closed OpenAL");
		Main.audio.destroy();
		
		// Send some info to stdout
		System.out.println("Mainloop closed normally");
	}

	@Override
	public void onEarly() {
		mspf -= 1;
		if(mspf < max_mspf) mspf = max_mspf;
	}

	@Override
	public void onLate() {
		mspf += 1;
		
		// Dont let the fps go past 1 frame every 10 seconds
		if(mspf > 10000) {
			mspf = 10000;
		}
	}

	@Override
	public void onStart() {
		System.out.println("Mainloop started");
	}

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

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

	@Override
	public void MainLoopUpdate()
	{
		// Stop the mainloop if the window should close
		if(Main.window.shouldClose()) Main.mainloop.stop();
		
		// Autosave every minute
		autosave_interval += 1;
		if(autosave_interval > 6000)
		{
			autosave_interval -= 6000;
			
			Main.world.save();
		}
	}

}
