using UnityEngine;
using System.Collections;

public class MineAlt1Controller : MonoBehaviour, IInteractable, IResetable
{
	private Animator animator;
	private bool flashing = false;
	private bool kill = false;
	[SerializeField]
	private float timerStart = 4f;
	private float timerCurrent;
	[SerializeField]
	private float boomTimerStart = 1f;
	private float boomTimerCurrent;

	void Start ()
	{
		animator = GetComponent<Animator>();
		timerCurrent = timerStart;
		boomTimerCurrent = boomTimerStart;
	}

	void Update()
	{
		if(Input.GetKeyDown(KeyCode.Space))
		{
			Reset();
		}
		if(flashing)
		{
			timerCurrent -= Time.deltaTime;
			if(timerCurrent <= 0)
			{
				Boom();
			}
		}
	}

	void OnTriggerEnter2D(Collider2D collider)
	{
		if(collider.CompareTag("Player"))
		{
			flashing = true;
			StartRandomColourAnimation();
		}
	}
	
	void OnTriggerStay2D(Collider2D collider)
	{
		if(kill && collider.CompareTag("Player"))
		{
			Debug.Log("Kill Player");
		}
	}
	
	void OnTriggerExit2D(Collider2D collider)
	{
		if(collider.CompareTag("Player"))
		{
			flashing = false;
			//StopAnimation();
		}
	}

	void OnCollisionEnter2D(Collision2D collision)
	{
		Debug.Log(collision.collider.tag);
		if(collision.collider.CompareTag("Player"))
		{
			Boom();
		}
	}

	public void StopAnimation()
	{
		animator.SetTrigger("reset");
	}

	private void Boom()
	{
		kill = true;
		animator.SetTrigger("boom");
	}

	public void Interact()
	{
		animator.SetTrigger("tick");
	}

	public void StartRandomColourAnimation()
	{
		if(flashing)
		{
			if(Random.Range(0,2) == 0)
			{
				animator.SetTrigger("flashRed");
				//Play red sound effect
			}
			else
			{
				animator.SetTrigger("flashGreen");
				//Play Green Sound efect
			}
		}
	}

	public void RemoveThis()
	{
		gameObject.GetComponent<SpriteRenderer>().enabled = false;
		foreach(Collider2D collider in gameObject.GetComponents<Collider2D>())
		{
			collider.enabled = false;
		}
		animator.ResetTrigger("flashRed");
		animator.ResetTrigger("flashGreen");
		animator.ResetTrigger("boom");
		animator.ResetTrigger("tick");
		flashing = false;
		timerCurrent = timerStart;
		animator.SetTrigger("reset");
	}
	
	public void Reset()
	{
		gameObject.GetComponent<SpriteRenderer>().enabled = true;
		foreach(Collider2D collider in gameObject.GetComponents<Collider2D>())
		{
			collider.enabled = true;
		}
	}
}
