using UnityEngine;
using System.Collections;

public class DeathSpawnController : MonoBehaviour {

	[SerializeField]
	Animator DeathAnimator = null;
	public GameObject SpawnPoint = null;
	public GameObject PlayerObject = null;
	[SerializeField]
	private AudioClip DeathSFX = null;
	private bool isPlayerAlive = true;
	private CharacterMovementController movementController;
	private CharacterInteractionController interactionController;
	[SerializeField]
	private Animator splat;

	// Use this for initialization
	void Start () 
	{
		DeathAnimator = GetComponent<Animator> ();
		movementController = gameObject.GetComponent<CharacterMovementController>();
		interactionController = gameObject.GetComponent<CharacterInteractionController>();
	}
	
	// Update is called once per frame
	void Update () 
	{
		
	}

	public void SpawnNewCharacter()
	{
		Debug.Log("Spawner called");
		if (!isPlayerAlive) 
		{
			Debug.Log ("New character");
			GetComponent<CharacterRandomiser> ().CreateNewPlayer ();
			//For now - generic placeholder
			GameObject NewPlayer = Instantiate (PlayerObject, SpawnPoint.transform.position, new Quaternion (0, 0, 0, 0)) as GameObject;
			NewPlayer.GetComponent<DeathSpawnController> ().SpawnPoint = this.SpawnPoint;
			//Just bug fixing hacks and things to make it look prettier in editor
			NewPlayer.tag = "Player";
			NewPlayer.name = "Character";
			gameObject.name = "DeadCharacter";
			NewPlayer.transform.localScale = new Vector3 (6, 6, 1);
			NewPlayer.GetComponent<CharacterRandomiser> ().UICharacterDescription = GetComponent<CharacterRandomiser> ().UICharacterDescription;
			NewPlayer.GetComponent<SpriteRenderer> ().color = new Color (Random.value, Random.value, Random.value);
			NewPlayer.GetComponent<DeathSpawnController> ().PlayerObject = this.PlayerObject;
			//Make this player redundent
			Destroy (GetComponent<Animator> ());
			foreach (MonoBehaviour mono in GetComponentsInChildren<MonoBehaviour>()) {
					Destroy (mono);
			}
		}
	}

	public void KillPlayer()
	{
		if (isPlayerAlive)
		{
			splat.transform.parent = null;
			splat.SetTrigger("splat");
			movementController.canMove = false;
			interactionController.canInteract = false;
			isPlayerAlive = false;
			Debug.Log ("Player death");
			DeathAnimator.SetTrigger ("Die");
			Destroy (GetComponent<BoxCollider> ());
			Destroy (GetComponent<Rigidbody> ());
			Destroy (GetComponent<CharacterMovementController> ());
			Destroy (GetComponent<CharacterInteractionController> ());
			Camera.main.GetComponent<AudioController> ().PlaySoundEffect (DeathSFX);
		}
	}

	public void UpdateSpawnPoint(GameObject SpawnPoint)
	{
		this.SpawnPoint = SpawnPoint;
	}
}
