using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {
	
	const int BULLET_BUFFER = 200;
	static Bullet[] bullet;
	static TexturePacker texture;
	float animationTime = 0;
	const float ANIMATION_TIME = 0.04f;
	
	Sprite[] animationSprite = new Sprite[8];
	
	int frame = 0;
	bool activeBullet = false;
	Vector3 velocity = Vector3.left;
	static int current = 0;
	
	public static void CreateBullets() {
		texture = new TexturePacker("Textures/objects", "Textures/objects_atlas");
		bullet = new Bullet[BULLET_BUFFER];
		GameObject buffer = new GameObject();
		buffer.transform.position = Vector3.zero;
		buffer.name = "Buffer";
		for(int i = 0; i < bullet.Length; i++) {	
			GameObject spriteObject = new GameObject();
			spriteObject.name = "bullet";
			spriteObject.transform.parent = buffer.transform;
			spriteObject.transform.localPosition = new Vector3(0, 50);			
			bullet[i] = spriteObject.AddComponent<Bullet>();
		}
	}
	
	public static void Fire(Vector3 position) {
		bullet[current].transform.position = position;
		bullet[current].velocity = Vector3.right * 60f;
		bullet[current].activeBullet = true;
		current++;
		if (current >= bullet.Length)
			current = 0;
	}
	
	void Awake () {
		for(int i = 0; i < animationSprite.Length; i++) {
			animationSprite[i] = Sprite.Create(
				transform, new Vector2(3.00f, 0.425f), 
				texture.SpriteByName("bullet_0" + (i + 1).ToString()));
			animationSprite[i].visible = false;
		}
		frame = Random.Range(0, 7);
	}
	
	void Update () {
		if (activeBullet) {
			Vector3 position = transform.localPosition;
			transform.localPosition = position + velocity * Time.deltaTime;
			if (position.x < -Control.cameraHeight * 2f)
				activeBullet = false;
			if (position.x >  Control.cameraHeight * 2f)
				activeBullet = false;
			if (position.y < -Control.cameraHeight)
				activeBullet = false;
			if (position.y >  Control.cameraHeight)
				activeBullet = false;
			animationTime -= Time.deltaTime;
			if (animationTime <= 0) {
				animationTime = ANIMATION_TIME;
				animationSprite[frame].visible = false;
				frame--;
				if (frame < 0)
					frame = 7;
				animationSprite[frame].visible = true;
			}
		}
	}
}
