package org.ronlievens.flappybird;

import org.ronlievens.flappybird.graphics.Shader;
import org.ronlievens.flappybird.level.Level;
import org.ronlievens.flappybird.math.Matrix4f;

import java.util.logging.Logger;

abstract class Game
{
	private final static Logger LOGGER = Logger.getLogger(Game.class.getName());
	final private double ns = 1000000000.0 / 60.0;
	private Level level;
	private long lastTime;
	private double delta;
	private long timer;
	private int updates;
	private int frames;

	protected void gameInit()
	{
		Shader.loadAll();

		Matrix4f pr_matrix = Matrix4f.orthographic(-10.0f, 10.0f, -10.0f * 9.0f / 16.0f, 10.0f * 9.0f / 16.0f, -1.0f, 1.0f);
		Shader.BG.setUniformMat4f("pr_matrix", pr_matrix);
		Shader.BG.setUniform1i("tex", 1);

		Shader.BIRD.setUniformMat4f("pr_matrix", pr_matrix);
		Shader.BIRD.setUniform1i("tex", 1);

		Shader.PIPE.setUniformMat4f("pr_matrix", pr_matrix);
		Shader.PIPE.setUniform1i("tex", 1);

		level = new Level();

		lastTime = System.nanoTime();
		delta = 0.0;
		timer = System.currentTimeMillis();
		updates = 0;
		frames = 0;
	}

	protected void gameupdate()
	{
		long now = System.nanoTime();
		delta += (now - lastTime) / ns;
		lastTime = now;
		if (delta >= 1.0)
		{
			level.update();
			updates++;
			delta--;
		}
		gameRender();
		frames++;
		if (System.currentTimeMillis() - timer > 1000)
		{
			timer += 1000;
			LOGGER.finest(updates + " ups, " + frames + " fps");
			updates = 0;
			frames = 0;
		}
	}

	private void gameRender()
	{
		level.render();
	}
}
