package zero1hd.polyjet.entity.enemies;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.Pool.Poolable;

import zero1hd.polyjet.Polyjet;
import zero1hd.polyjet.entity.Entities;
import zero1hd.polyjet.entity.Entity;

public class Flake extends Actor implements Poolable, Entity {
	private Texture texture;
	private float rate;
	private float timer;
	private float totalTime;
	private Shard[] shards;
	private Rectangle hitbox;
	private Vector2 center;
	private Vector2 rot;
	
	public Flake(Texture texture) {
		this.texture = texture;
		hitbox = new Rectangle();
		center = new Vector2();
		rot = new Vector2();
	}
	
	public void init(float x, float y, float rate, float fuse, float angle, Shard... shards) {
		this.shards = shards;
		setSize(3f, 3f);
		this.rate = rate;
		this.timer = fuse;
		this.totalTime = fuse;
		hitbox.setSize(getWidth(), getHeight());
		center.set(getWidth()/2f, getHeight()/2f);
		setPosition(x-center.x, y-center.y);
		rot.set(MathUtils.sinDeg(angle), MathUtils.cosDeg(angle));
	}
	
	@Override
	public void act(float delta) {
		if (timer > 0) {
			timer -= delta;
		}
		moveBy(rot.x*delta*rate, rot.y*delta*rate);
		for (int i = 0; i < shards.length; i++) {
			shards[i].setPosition(getX()+center.x-shards[i].getCenter().x, getY()+center.y-shards[i].getCenter().y);
		}
		
		hitbox.setPosition(getX(), getY());
		
		if (getX() > Polyjet.GAME_AREA_WIDTH || getY() > Polyjet.GAME_AREA_HEIGHT || getX() < 0-getWidth() || getY() < 0-getHeight()) {
			timer = 0;
		}
		super.act(delta);
	}
	
	@Override
	public void draw(Batch batch, float parentAlpha) {
		batch.setColor(0.25f,0.25f,0.25f,1f- timer/totalTime);
		batch.draw(texture, getX(), getY(), getWidth(), getHeight());
		batch.setColor(Color.WHITE);
		super.draw(batch, parentAlpha);
	}
	
	@Override
	public void collided(Entity entity) {
		switch (entity.getEntityType()) {
		case LASER:
			timer --;
			break;
		default:
			break;
		}
	}

	@Override
	public Rectangle getHitZone() {
		return hitbox;
	}

	@Override
	public Entities getEntityType() {
		return Entities.FLAKE;
	}

	@Override
	public boolean isDead() {
		if (timer <= 0) {
			for (int i = 0; i < shards.length; i++) {
				shards[i].setRate(45f);
			}
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void reset() {
		rate = 0;
		timer = 0;
		shards = null;
		hitbox.set(0, 0, 0, 0);
		setPosition(0, 0);
		setSize(0, 0);
		center.set(0, 0);
		rot.set(0, 0);
		totalTime = 0;
	}

}
