package de.heatup.objects;

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

import de.heatup.logging.Logger;
import de.heatup.ui.PanelBuilder;
import de.heatup.ui.StatusPanelAdder;

public class PowerUp extends StaticObject {
	
	/**
	 * Warum auch immer ist JComponent per default serialisierbar
	 */
	private static final long serialVersionUID = 1L;
	
	private int pType;
	private boolean triggered = false;
	private boolean triggeredByPlayer = false;
	
	private static int tickCount = 0;
	private static int tickRoundMax = 10000;
	private static int resetTickstamp = 0;

	public PowerUp() {
		super('b', new Point());
		Random rand = new Random();
		this.pType = rand.nextInt(PowerUpController.getAvailablePUs());
	}
	public void spawnAt(Point spawnPoint) {
		this.currentGridPosition = spawnPoint;
		super.setAutoBounds(spawnPoint.x*25, spawnPoint.y*25);
		PanelBuilder.getGamePanel().setComponentZOrder(this, 1);
		this.repaint();
	}
	public Point getGridLocation() {
		return currentGridPosition;
	}
	public void kill() {
		StatusPanelAdder.setPUText(" ");
		PanelBuilder.getGamePanel().remove(this);
		PanelBuilder.getGamePanel().repaint();
	}
	public boolean isTriggered() {
		return triggered;
	}
	public void tick() {
		tickCount++;
		if (tickCount>=tickRoundMax) {
			tickCount = 0;
		}
		int remainingTicks;
		if (tickCount > resetTickstamp) {
			remainingTicks = tickRoundMax - tickCount + resetTickstamp;
		} else {
			remainingTicks = resetTickstamp - tickCount;
		}
		this.setActiveCountdown(remainingTicks/60);
		if (this.isTriggered() && tickCount == resetTickstamp) {
			PowerUpController.deactivate(pType, triggeredByPlayer);
			PowerUpHandler.removePowerUp();
		}
	}
	public void trigger(boolean byPlayer) {
		if (!this.isTriggered()) {
			this.triggered = true;
			this.triggeredByPlayer = byPlayer;
			resetTickstamp = tickCount+60*(PowerUpController.getDuration(pType));
			Logger.write("duration: "+PowerUpController.getDuration(pType));
			resetTickstamp = PowerUpHandler.checkStamp(resetTickstamp);
			PowerUpController.activate(pType, byPlayer);
			Logger.write("Triggered - Trigger resetTickstamp: "+resetTickstamp); // das alte objekt wird offensichtlich immer wieder recycled, sollte aber kein problem darstellen.
			this.kill();
		}
	}
	public void setRemainingTime(int time) {
		if (!this.isTriggered()) {
			StatusPanelAdder.setPUText("despawn in "+time);
		}
	}
	private void setActiveCountdown(int time) {
		StatusPanelAdder.setPUText(PowerUpController.getName(pType) + " active for " +time);
	}
}
