package de.heatup.objects;

import java.awt.Point;
import java.util.Random;

import de.heatup.logging.Logger;
import de.heatup.mapengine.SpawnAssistant;
import de.heatup.ui.PanelBuilder;

public class PowerUpHandler {
	private static boolean puSpawned = false;
	private static boolean firstRound = true;
	private static int tickCount = 0;
	private static int tickRoundMax = 10000;
	private static int resetTickstamp = 0;
	private static PowerUp pu = null;
	private static Random rand = new Random();
	public static void tick() {
		tickCount++;
		if (tickCount>=tickRoundMax) {
			tickCount = 0;
		}
		if (puSpawned) {
			int remainingTicks;
			if (tickCount > resetTickstamp) {
				remainingTicks = tickRoundMax - tickCount + resetTickstamp;
			} else {
				remainingTicks = resetTickstamp - tickCount;
			}
			pu.setRemainingTime(remainingTicks/60);
			if (pu.isTriggered()) {
				pu.tick();
			}
		}
		if (!firstRound) {
			if (tickCount == resetTickstamp && !puSpawned) {
				createPowerUp();
			}
			
			if (tickCount == resetTickstamp && puSpawned) {
				if (!pu.isTriggered()) {
					removePowerUp();
				}
			}
		} else {
			firstRound = false;
			resetTickstamp = tickCount+60*(rand.nextInt(10)+15);
			resetTickstamp = checkStamp(resetTickstamp);
		}
	}
	protected static int checkStamp(int stamp) {
		if (stamp > tickRoundMax) {
			return stamp % tickRoundMax;
		} else {
			return stamp;
		}
	}
	public static void createPowerUp() {
		Point sp = SpawnAssistant.getPathLocationOnGrid();
		pu = new PowerUp();
		pu.setBounds(25, 25, 25, 25);
		PanelBuilder.getGamePanel().add(pu);
		pu.spawnAt(sp);
		resetTickstamp = tickCount+60*(rand.nextInt(15)+15);
		resetTickstamp = checkStamp(resetTickstamp);
		puSpawned = true;
	}
	public static void removePowerUp() {
		pu.kill();
		pu = null;
		resetTickstamp = tickCount+60*(rand.nextInt(15)+15);
		resetTickstamp = checkStamp(resetTickstamp);
		puSpawned = false;
	}
	public static Point getPowerUpGridLocation() {
		if (pu == null) {
			return new Point(-1,-1);
		} else {
			return pu.getGridLocation();
		}
	}
	public static PowerUp getPowerUp() {
		return pu;
	}
}
