using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Particle : MonoBehaviour {
    // Variables
    public float activeDuration = 2.0f;
    public float collidableDuration = 2.0f;
	public float fadeOutDuration = 3f;
    public float randomVariance = 50f;
	// References
	private BoxCollider2D myBoxCollider2D;
	private Rigidbody2D myRigidbody2D;
	private SpriteRenderer mySpriteRenderer;
	private Transform myTransform;
    private Color myStartColor;
	// Properties
	private float _activeDuration;
    private float _timestamp;
    private Vector3 _scaleFactor = new Vector3(0.01f, 0.01f, 0.01f);

    // ========================= Initialization =========================
    // Use this for initialization
    void Start () {}

	public void Initialize(Color color, float duration, float variance) {
		// Cache references
		myBoxCollider2D = GetComponent<BoxCollider2D>();
		myRigidbody2D = GetComponent<Rigidbody2D>();
		mySpriteRenderer = GetComponent<SpriteRenderer>();
        mySpriteRenderer.color = color;
        myStartColor = color;
        myTransform = this.gameObject.transform;
        fadeOutDuration = duration;
        randomVariance = variance;
        this.gameObject.SetActive(false);

    }
	
	// ========================= Update =========================
	public void Activate (Vector3 position, Vector3 direction) {
        _timestamp = Time.time;

		// Enable the particle
		_activeDuration = activeDuration;
		this.gameObject.SetActive(true);

		// Reset particle
		myBoxCollider2D.enabled = false;
        myTransform.localScale = new Vector3(1f, 1f, 1f);

        // Set particles position and direction
        myTransform.position = position;
		myTransform.rotation = Quaternion.Euler(0.0f, 0.0f, Random.Range(0.0f, 360.0f));
		myRigidbody2D.AddForce(new Vector3((direction.x + Random.Range(-randomVariance, randomVariance)) * -0.5f,
		                                   (direction.y + Random.Range(-randomVariance, randomVariance)) * -0.5f, 0f));
	}

	void Update() {
		// If particle is active, slowly fade out
		if (_activeDuration >= 0) {
			_activeDuration -= Time.deltaTime;
            myTransform.localScale = myTransform.localScale + _scaleFactor;
            mySpriteRenderer.color = Color.Lerp(myStartColor, new Color(1, 1, 1, 0f), (Time.time - _timestamp) / fadeOutDuration);

            if (_activeDuration <= 0) {
				this.gameObject.SetActive(false);
			}
			else if (_activeDuration <= collidableDuration) {
				myBoxCollider2D.enabled = true;
			}
		}
	}
}
