using UnityEngine;
using System.Collections.Generic;

public class RocketParticleGenerator : MonoBehaviour {
	// Constants
	private const int NUM_PARTICLES = 20;
	private const float TIME_BETWEEN_NEW_SPAWNS = 0.1f;
    // References
    public GameObject particlePrefab;
    private Transform myTransform;
    private Rigidbody2D myRigidBody;
    // Properties
    private List<Particle> _particles;
	public float _timeUntilNewSpawn; // Prevents particles from spawning too much
    private int _currentIndex;
    public float fadeOutDuration;
    public float randomVariance;

    // ========================= Initialization =========================
    // Use this for initialization
    void Start () {
		// Set references
		myTransform = this.gameObject.transform;
        myRigidBody = GetComponent<Rigidbody2D>();
        SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();

        // Create pool of particles
        _currentIndex = 0;
        _particles = new List<Particle>();
        for (int i = 0; i < NUM_PARTICLES; ++i) {
            GameObject newParticleObject = Instantiate(particlePrefab);
            Particle newParticle = newParticleObject.GetComponent<Particle>();
            newParticle.Initialize(spriteRenderer.color, fadeOutDuration, randomVariance);
            _particles.Add(newParticle);
        }
    }
		
	// ========================= Methods =========================
	public void SpawnParticle(Vector3 direction) {
		if (_timeUntilNewSpawn <= 0f) {
			// Reset spawn timer
			_timeUntilNewSpawn = TIME_BETWEEN_NEW_SPAWNS;

			// Turn on a particle
			if (_currentIndex < _particles.Count) {
				_particles[_currentIndex].Activate(myTransform.position, direction);
			}

			// Iterate to next particle index
			_currentIndex++;
			if (_currentIndex >= _particles.Count) {
				_currentIndex = 0;
			}
		}
	}

	void Update() {
		_timeUntilNewSpawn -= Time.deltaTime;
        this.SpawnParticle(myRigidBody.velocity);
    }
}
