package zero1hd.rhythmbullet.entity.enemies;

import java.util.HashMap;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Rectangle;

import zero1hd.rhythmbullet.entity.Entity;
import zero1hd.rhythmbullet.entity.ally.Laser;

public class Flake extends Entity {
	private float timer;
	private float totalTime;
	private Shard[] shards;
	
	@Override
	public void preInit() {
		sprite = new Sprite(assets.get("flake.png", Texture.class));
		simple = true;
		enemy = true;
		move = false;
		setSize(3f, 3f);
		sprite.setSize(getWidth(), getHeight());
		super.preInit();
	}
	
	public void init(float x, float y, float rate, float fuse, float angle, int shardCount) {
		this.shards = new Shard[shardCount];
		for (int i = 0; i < shards.length; i++) {
			shards[i] = ec.shard.buildEntity();
			shards[i].init(x, y, 360/shards.length*i, 0, 2);
			ec.getStage().addActor(shards[i]);
		}
		
		this.speed = rate;
		this.timer = fuse;
		this.totalTime = fuse;
		this.angle = angle;
		setPosition(x-getWidth()/2f, y-getHeight()/2f);
		
	}
	
	/**
	 * params: shardCount, x, y, rate, fuse, angle;
	 */
	@Override
	public void init(HashMap<String, Float> params) {
		this.shards = new Shard[params.get("shardCount").intValue()];
		for (int i = 0; i < shards.length; i++) {
			shards[i] = ec.shard.buildEntity();
			shards[i].init(params.get("x"), params.get("y"), 360/shards.length*i, 0, 1);
			ec.getStage().addActor(shards[i]);
		}
		this.speed = params.get("rate");
		this.timer = params.get("fuse");
		this.totalTime = timer;
		this.angle = params.get("angle");
		hitbox.setSize(getWidth(), getHeight());
		setPosition(params.get("x")-getWidth()/2f, params.get("y")-getHeight()/2f);
		super.init(params);
	}
	
	@Override
	public void act(float delta) {
		if (timer > 0) {
			timer -= delta;
		}
		
		move(delta, true);
		for (int i = 0; i < shards.length; i++) {
			shards[i].setPosition(center.x-shards[i].getWidth()/2f, center.y-shards[i].getWidth()/2f);
			shards[i].move(delta, true);
		}
		
		if (timer <= 0) {
			for (int i = 0; i < shards.length; i++) {
				shards[i].setSpeed(30f);
			}
			dead = true;
		}
		
		super.act(delta);
	}
	
	@Override
	public void draw(Batch batch, float parentAlpha) {
		sprite.setColor(0f, 0f, 0f, 1-(timer/totalTime));
		super.draw(batch, parentAlpha);
	}
	
	@Override
	public void collided(Entity entity) {
		if (entity.getClass() == Laser.class) {
			dead = true;
			for (int i = 0; i < shards.length; i++) {
				shards[i].kill();
			}
		}
	}

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

	@Override
	public void reset() {
		timer = 0;
		shards = null;
		totalTime = 0;
		super.reset();
	}

}
