using UnityEngine;
using System.Collections;

public class Carryable : MonoBehaviour {

    // Exposed variables & types
    //--------------------------------

    [SerializeField] string m_typeId;
    [SerializeField] Collider2D m_triggerCollision = null;
    [SerializeField] AudioCue m_soundPickUp = null;
	[SerializeField] AudioCue m_soundDrop = null;

    // Private variables 
    //--------------------------------

    Animator m_animator = null;
    Rigidbody2D m_rigidBody = null;

	bool m_carrying = false;
    bool m_everPickedUp = false;

    float m_blockPickupTimer = 0.0f;
    
    // Public methods 
    //--------------------------------

    public string GetTypeId()
    {
        return m_typeId;
    }

    public Vector2 GetSize()
    {
        return GetComponentInChildren<SpriteRenderer>().bounds.size;
    }

    public bool IsCarrying()
    {
        return m_carrying;
    }

    public void OnDrop()
    {
        transform.SetParent(null);

        m_carrying = false;

        m_triggerCollision.enabled = true;

        m_rigidBody = gameObject.AddComponent<Rigidbody2D>();

        #if !UNITY_5_0_0
            m_rigidBody.constraints |= RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezeRotation;
        #endif
    }


    public void OnPickup()
    {
		if ( m_carrying == false && m_everPickedUp == false)
			SystemAudio.Play(m_soundPickUp);

        if (m_animator)
        {
            m_animator.Play("Pickup");            
        }

		m_everPickedUp = true;

        m_carrying = true;

        Destroy(m_rigidBody);

        m_triggerCollision.enabled = false;
    }

    public AudioCue GetDropSound() { return m_soundDrop; }
    
    // Private methods 
    //--------------------------------

    void Awake()
    {
        m_animator = GetComponent<Animator>();
        m_rigidBody = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (m_blockPickupTimer > 0.0f)
        {
            m_blockPickupTimer -= Time.deltaTime;            
        }
    }

    void OnTriggerEnter2D(Collider2D collider)
    {
        if (!m_carrying && m_blockPickupTimer <= 0.0f)
        {
            BodyBlock bodyBlock = collider.gameObject.GetComponent<BodyBlock>();
            if (bodyBlock && !bodyBlock.IsCarrying())
            {
                bodyBlock.StartCarrying(this);
            }
        }
    }
}
