package de.frajul.endlessroll.entities.tools;

import de.frajul.endlessroll.data.Vector;
import de.frajul.endlessroll.entities.DestroyEffect;
import de.frajul.endlessroll.entities.Obstacle;
import de.frajul.endlessroll.entities.Player;
import de.frajul.endlessroll.entities.collision.geometry.Geometry;
import de.frajul.endlessroll.main.GameLog;
import de.frajul.endlessroll.main.game.Timer;

/**
 * Created by Julian on 20.02.2016.
 */
public class Bomb extends Tool {

    private float delta;
    private boolean exploding = false;
    private Obstacle attachedObstacle;
    private Vector offsetToObstaclePosition = new Vector();

    public Bomb(Vector position) {
        super(ToolType.BOMB, position, .25f, .25f, false, false);
        animation.setIndexSequence(new int[]{0, 1, 2});
        animation.setLooping(false);
        animation.setRequiredDelta(
                (int) (ToolType.BOMB.getCurrentUpgradeValue(ToolUpgradeType.DURATION) / 3f));
    }

    @Override
    public void update(Timer timer) {
        super.update(timer);
        float explosionDuration = ToolType.BOMB.getCurrentUpgradeValue(ToolUpgradeType.DURATION);
        delta += timer.getFrameTimeSeconds();
        int currentExplosionState = Math.min((int) (delta / (explosionDuration / 3f)), 3);
        if (attachedObstacle != null) {
            if(attachedObstacle.isMoving())
                super.setPosition(new Vector(attachedObstacle.getPosition()).translate(offsetToObstaclePosition));
            attachedObstacle.setBombExplosionState(currentExplosionState);
        }
        if (delta >= explosionDuration)
            exploding = true;
    }

    @Override
    public void onPlayerCollision(Player player, Timer timer) {
    }

    @Override
    protected Geometry createWorldCollisionBounds() {
        return this;
    }

    @Override
    protected Geometry createPlayerCollisionBounds() {
        return this;
    }

    public void setAttachedObstacle(Obstacle attachedObstacle) {
        this.attachedObstacle = attachedObstacle;
        offsetToObstaclePosition = attachedObstacle.getPosition().vectorTo(super.getPosition());
        attachedObstacle.setBombExplosionState(0);
    }

    public boolean isExploding() {
        return exploding;
    }

    public void explode() {
        if (attachedObstacle != null)
            attachedObstacle.destroy(DestroyEffect.EXPLOSION);
        super.destroy(DestroyEffect.EXPLOSION);
    }
}
