using UnityEngine;
using UnityEngine.Events;
using System.Collections;

public class Killzone : MonoBehaviour
{
	public Rigidbody2D rb2D;
	public Collider2D killerCollider;

	public AudioClip hitSound;
	public AudioClip colisionSound;

	public AudioClip laugh;

	public static UnityEvent OnKill = new UnityEvent();

	private void Awake()
	{
		rb2D = GetComponentInChildren<Rigidbody2D>();
	}

	private void FixedUpdate()
	{
		if(rb2D != null && killerCollider != null) killerCollider.enabled = (rb2D.velocity.y < -30f);
	}

	private void OnTriggerEnter2D(Collider2D other)
	{
		if(other.CompareTag("Player"))
		{
			OnKill.Invoke();

			//print(gameObject + " x> " + other.gameObject);
			other.GetComponentInChildren<Animator>().SetBool("Die", true);
			Invoke("Respawn", 1);

			if(hitSound != null) AudioSource.PlayClipAtPoint(hitSound, Camera.main.transform.position, 0.5f);
			if(laugh != null) AudioSource.PlayClipAtPoint(laugh, Camera.main.transform.position, 0.5f);
		}
	}

	private void OnCollisionEnter2D(Collision2D col)
	{
		if(colisionSound != null && !col.collider.CompareTag("Player"))
		{
			AudioSource.PlayClipAtPoint(colisionSound, Camera.main.transform.position, 0.5f);
		} 
	}

	private void Respawn()
	{
		Respawner.instance.Respawn();
	}
}