package main.entities;

import java.util.ArrayList;

import ea.Vektor;
import main.Main;
import main.SheetLoader;

public class Snake extends LivingEntity {

	private static SheetLoader loader = new SheetLoader("/res/images/snake_spritesheet_calciumtrice.png", 32, 32,
			new int[] { 10, 10, 10, 10, 10, 8 });

	public Snake() {
		super(loader.getFigur(0), "idle");

		posX = 9f;
		posY = 9f;
		accelleration = 0.006f;
		spriteOffsetY = -0.6f;
		width = 0.65f;
		height = 0.8f;
		mirrored = true;

		actionFigur.neuerZustand(loader.getFigur(1), "lost_sight");
		actionFigur.neuerZustand(loader.getFigur(2), "walk");
		actionFigur.neuerZustand(loader.getFigur(3), "attack");
		actionFigur.neuerZustand(loader.getFigur(4), "die");
		actionFigur.neuerZustand(loader.getFigur(5), "damage");
	}

	@Override
	protected void update() {
		ArrayList<Entity> entities = Main.instance.getWorld().getCurrentMap().getEntities();
		Entity nearestPlayer = null;
		for (Entity e : entities) {
			if (e instanceof Player) {
				if (nearestPlayer == null || e.dist(this) < nearestPlayer.dist(this)) {
					nearestPlayer = e;
				}
			}
		}
		if (nearestPlayer != null && lineOfSightClear(nearestPlayer) && !actionFigur.aktuellesVerhalten().equals("damage")) {
			if (dist(nearestPlayer) < 1f) {
				zustandSetzen("attack");
			} else {
				if (actionFigur.aktuellesVerhalten().equals("attack")) {
					actionFigur.aktuelleFigur().animationsBildSetzen(0);
				}
				Vektor toPlayer = new Vektor(nearestPlayer.posX - posX, nearestPlayer.posY - posY);
				toPlayer = toPlayer.normiert();
				velX += toPlayer.x * accelleration;
				velY += toPlayer.y * accelleration;
				zustandSetzen("walk");
			}
		} else {
			if (actionFigur.aktuellesVerhalten().equals("walk")) {
				zustandSetzen("lost_sight");
			}
			if (actionFigur.aktuellesVerhalten().equals("lost_sight") && actionFigur.aktuelleFigur()
					.aktuellesBild() == actionFigur.aktuelleFigur().animation().length - 1) {
				actionFigur.aktuelleFigur().animationsBildSetzen(0);
				zustandSetzen("idle");
			}
		}
		if (actionFigur.aktuellesVerhalten().equals("damage") && actionFigur.aktuelleFigur().aktuellesBild() < actionFigur.aktuelleFigur().animation().length - 1){
			zustandSetzen("walk");
		}
		this.checkTileCollisions(Main.instance.getWorld().getCurrentMap());
		super.update();
	}

	@Override
	public void takeDamage(float damage) {
		zustandSetzen("damage");
		super.takeDamage(damage);
	}
}
