using UnityEngine;
using System.Collections;

//attach to any object in the game which takes damage (player, enemies, breakable crates, smashable windows..)
//[RequireComponent(typeof(AudioSource))]
public class Health : MonoBehaviour 
{

	public PlayerBase pBase;						// player base reference
	//public AudioClip impactSound;					//play when object imacts with something else
	//public AudioClip hurtSound;						//play when this object recieves damage
	//public AudioClip deadSound;						//play when this object dies
	public float hitFlashDelay = 0.1f;				//how long each flash lasts (smaller number = more rapid flashing)
	public float flashDuration = 0.9f;				//how long flash lasts (object is invulnerable to damage during this time)
	public Color hitFlashColor = Color.red;			//color object should flash when it takes damage
	public Transform flashObject;					//object to flash upon receiving damage (ie: a child mesh). If left blank it defaults to this object.
	
	[HideInInspector]
	public bool flashing;
	
	private Color originalColor;
	private bool hitColor = false;
	private float nextFlash, stopFlashTime, h;
	private Renderer flashRender;
	private AudioSource aSource;
	
	//setup
	void Awake()
	{
		//aSource = GetComponent<AudioSource>();
		//aSource.playOnAwake = false;
		if(flashObject == null)
			flashObject = transform;
		flashRender = flashObject.GetComponent<Renderer>();
		originalColor = flashRender.material.color;
	}
	
	//detecting damage and dying
	void Update()
	{		
		//flash if we took damage
		if (pBase.playerHealth < h) {
			flashing = true;
			stopFlashTime = Time.time + flashDuration;
			//if (hurtSound)
				//AudioSource.PlayClipAtPoint(hurtSound, transform.position);
		}
		h = pBase.playerHealth;
		
		//flashing
		if (flashing) {
			Flash ();
			if (Time.time > stopFlashTime) {
				flashRender.material.color = originalColor;
				flashing = false;
			}
		}
	}
	
	//toggle the flashObject material tint color
	void Flash () {
		flashRender.material.color = (hitColor) ? hitFlashColor : originalColor;
		if(Time.time > nextFlash) {
			hitColor = !hitColor;
			nextFlash = Time.time + hitFlashDelay;
		}
	}
	
	//respawn object, or destroy it and create the SpawnOnDeath objects
	void Death () {
		//if (deadSound)
		//	AudioSource.PlayClipAtPoint(deadSound, transform.position);
		flashing = false;
		flashObject.GetComponent<Renderer>().material.color = originalColor;
	}
}
