package ch.marc.jumpguy;

import java.awt.Color;
import java.util.ArrayList;

import ch.marc.jumpguy.entities.Camera;
import ch.marc.jumpguy.entities.Entity;
import ch.marc.jumpguy.entities.Level;
import ch.marc.jumpguy.entities.WorldBlock;
import ch.marc.jumpguy.gui.Frame;
import ch.marc.jumpguy.gui.GamePanel;

public class MainLoop {
	Frame mainGUI;
	GamePanel pan;
	Camera cam;
	ArrayList<WorldBlock> blocks;
	ArrayList<Entity> ents;
	Level lvl;
	int levelN;
	boolean firstframe = true;

	public void start() {

		mainGUI = new Frame();// Creates Window
		pan = mainGUI.pan; // Gets the JPanel from the Window

		cam = new Camera();
		pan.camera = cam;// Set the camera from the Panel

		blocks = new ArrayList<WorldBlock>();

		levelN = 1;
		loadLevel(levelN);

		blocks = lvl.blocks;

		pan.worldBlocks = blocks;

		pan.player = mainGUI.play;// Passes the Player object from the JFrame to
									// the JPanel

		// Main Game loop
		for (;;) {
			long measure1 = System.currentTimeMillis();
			updateEntities();
			updatePlayer();
			updateCamera();
			renderFrame();
			long measure2 = System.currentTimeMillis();
			if (measure2 - measure1 >= 17) {
			} else {
				try {
					Thread.sleep(17 - (measure2 - measure1));// Limits it to 60
																// FPS
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}

	private void loadLevel(int levelnumber) {
		if (levelnumber > GloabalVars.levelcount) {
			lvl = new Level("levels/end.lvl");
		} else {
			lvl = new Level("levels/level" + levelnumber + ".lvl");

		}
		reloadLevel();
	}

	private void reloadLevel() {
		blocks = lvl.blocks;
		ents = lvl.ents;
		pan.worldBlocks = blocks;
		pan.ents = ents;
		mainGUI.play.x = lvl.playerX;
		mainGUI.play.y = lvl.playerY;
		pan.camera.x = lvl.playerX - 425;
		pan.camera.y = lvl.playerY - 200;
		pan.setBackground(Color.decode(lvl.col));
	}

	private void renderFrame() {
		pan.repaint();
	}

	private void updateCamera() {// Gives the new camera data to the JPanel
		pan.camera.updateCamera(mainGUI.play.x, mainGUI.play.y,
				mainGUI.play.speed, (int) mainGUI.play.maxvertspeed);
	}

	private void updatePlayer() {// Updates the playerstate and gives the
									// updated one to the JPanel
		mainGUI.play.updateState(blocks, ents, lvl.dieheight);
		if (mainGUI.play.dead) {
			reloadLevel();
			mainGUI.play.dead = false;
		} else if (mainGUI.play.win) {
			mainGUI.play.win = false;
			levelN++;
			loadLevel(levelN);
		}
		if (firstframe) {
			mainGUI.play.x = lvl.playerX;
			mainGUI.play.y = lvl.playerY;
			firstframe = false;
		}
	}

	public void updateEntities() {
		for (Entity ent : ents) {
			ent.updateState();
		}
		pan.ents = ents;
	}

	public void end() {
	}

}
