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

public class Killable : MonoBehaviour {
    [SerializeField]
    private float m_respawnTimeInSeconds = 5.0f;

    [SerializeField]
    private bool m_alive = true;
    private Animator m_animator;

	[SerializeField] private AudioClip[] m_DeathSounds;

    public bool alive
    {
        get { return m_alive; }
    }

	public void Kill() {
		Kill (null);
	}
	public void Kill(GameObject killer)
    {
		if (killer != null) {
			killer.GetComponent<ScoreCounter> ().OnKill (gameObject);
		}

        m_animator.SetTrigger("Death");

        GetComponent<ScoreCounter> ().OnKilled ();

		IAction[] actions = GetComponents<IAction> ();
		foreach (IAction a in actions) {
			if(a.GetType()!=typeof(SwordAttack) && a.GetType()==typeof(MonoBehaviour))
				Destroy ((MonoBehaviour) a);
		}

		var audio = GetComponent<AudioSource> ();
		if (audio != null && m_DeathSounds.Length>0) {
			audio.PlayOneShot(Util.RandomElement (m_DeathSounds));
		}

		m_alive = false;
		EnableComponents(false);
		StartCoroutine(Respawn());
    }

    private void EnableComponents(bool enable)
    {
        GetComponent<NinjaMovement>().enabled = enable;
        GetComponent<NinjaInputController>().enabled = enable;
		GetComponent<ScoreCounter> ().enabled = enable;
        //GetComponent<SpriteRenderer>().enabled = enable;
        foreach (var c in GetComponents<Collider2D>())
            c.enabled = enable;

        GetComponent<Rigidbody2D>().simulated = enable;
    }

    private IEnumerator Respawn()
    {
        yield return new WaitForSeconds(m_respawnTimeInSeconds);
        EnableComponents(true);
        m_alive = true;

        // Get all respawn points and spawn at random point
        var points = Util.Find<Transform>("RespawnPoints");
        if (points)
        {
            int randomChildIdx = Random.Range(0, points.childCount - 1);
            transform.position = points.GetChild(randomChildIdx).position;
        }
    }

	// Use this for initialization
	void Start () {
        m_animator = GetComponent<Animator>();
    }
	
	// Update is called once per frame
	void Update () {
		
	}
}
