package pl.shockah.ts.entities;

import pl.shockah.glib.geom.Rectangle;
import pl.shockah.glib.gl.Graphics;
import pl.shockah.glib.gl.color.Color;
import pl.shockah.glib.logic.standard.Entities;
import pl.shockah.glib.logic.standard.EntityCollidable;
import pl.shockah.ts.Assets;
import pl.shockah.ts.Main;
import pl.shockah.ts.entities.waterblur.IWaterBlur;
import pl.shockah.ts.entities.waterblur.WaterBlur;
import pl.shockah.ts.gameplay.Game;
import pl.shockah.ts.gameplay.ITimeAffected;

public class EntitySpikes extends EntityCollidable implements IWaterBlur,ITimeAffected {
	protected boolean[] sides = new boolean[4];
	protected int frame = 0;
	
	protected float rotateTimer = -1;
	protected double rotating = 0, angle = 0;
	
	public EntitySpikes() {
		baseDepth = 0d+.1d;
	}
	
	protected void onCreate() {
		shape = new Rectangle(pos.x,pos.y,24,24);
	}
	
	protected void onFirstUpdate() {
		for (int i = 0; i < sides.length; i++) sides[i] = false;
		for (EntityWall wall : Entities.getType(EntityWall.class)) {
			if (isSide(0,-1,wall)) sides[0] = true;
			if (isSide(0,1,wall)) sides[1] = true;
			if (isSide(-1,0,wall)) sides[2] = true;
			if (isSide(1,0,wall)) sides[3] = true;
		}
		for (int i = 0; i < 4; i++) frame += sides[i] ? 1<<i : 0;
		
		if (frame == 0 || frame == 3 || frame == 12 || frame == 15) rotateTimer = Main.rand.nextInt(120);
	}
	protected boolean isSide(int x, int y, EntityWall wall) {
		return wall.pos.x == pos.x+x*24 && wall.pos.y == pos.y+y*24;
	}
	protected void onUpdate() {
		double mod = Game.me.time.getSpeed(this);
		if (mod == 0) return;
		
		if (rotateTimer > 0) {
			rotateTimer -= 1*mod;
			if (rotateTimer <= 0 && rotateTimer > -1) {
				rotating = 3*(Main.rand.nextBoolean()?1:-1);
				rotateTimer = 120+Main.rand.nextInt(120);
			}
		}
		if (rotating != 0) {
			angle += rotating;
			if (angle >= 360) angle -= 360;
			if (angle < 0) angle += 360;
			
			if (angle%90 == 0) rotating = 0;
		}
	}
	
	protected void onRender(Graphics g) {
		g.setColor(Color.White.alpha(WaterBlur.blurAlpha));
		Assets.ssSpikes.getImage(frame).rotation.angle = angle;
		g.draw(Assets.ssSpikes.getImage(frame),pos.x,pos.y);
	}
	
	public boolean affectedSlow() {return true;}
	public boolean affectedStop() {return true;}
}