using UnityEngine;
using System.Collections;

public class TriggerTile : MonoBehaviour {

	[SerializeField] string m_triggerMessage = string.Empty;
	[SerializeField] string m_messageString = string.Empty;
	[SerializeField] float m_messageFloat = 0;
	[SerializeField] bool m_destroyOnTrigger = false;
    [SerializeField] bool m_hitFeet = false;
    [SerializeField] bool m_dinerTriggers = false;

    [SerializeField] bool m_triggerEffectAtTriggerer = false;
    [SerializeField] GameObject m_triggerEffect;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void OnTriggerEnter2D(Collider2D other)
	{
        if (string.IsNullOrEmpty(m_triggerMessage))
            return;

        bool isPlayer = other.transform != null && other.transform.root.name.Contains("Player");
        bool isDiner = other.transform != null && other.transform.root.name.Contains("Diner");
        
        if ( isPlayer || (isDiner && m_dinerTriggers) )
		{
			if ( m_hitFeet == false && other.transform.name == "Feet" )
				return;
            
            // HACK: LO!
            Player player = FindObjectOfType<Player>();

			if ( string.IsNullOrEmpty( m_messageString ) == false ) 
                player.transform.root.SendMessage(m_triggerMessage, m_messageString);
			else if ( m_messageFloat != 0 ) 
                player.transform.root.SendMessage(m_triggerMessage, m_messageFloat);
			else 
                player.transform.root.SendMessage(m_triggerMessage);

            bool triggered = true;
            ExitSprite exitSprite = GetComponentInChildren<ExitSprite>();
            if (exitSprite)
            {
                if (!exitSprite.IsOpen())
                {
                    triggered = false;
                }
            }

            if (triggered)
            {
                if (m_triggerEffect)
                {
                    if (m_triggerEffectAtTriggerer)
                    {
                        Instantiate(m_triggerEffect, other.transform.position, other.transform.rotation);                    
                    }
                    else
                    {
                        Instantiate(m_triggerEffect, transform.position, transform.rotation);                    
                    }
                }                
            }

			if ( m_destroyOnTrigger )
			{
				GameObject.Destroy(gameObject);
			}
		}		
	}
}
