using UnityEngine;
using System.Collections;

public class ExitSprite : MonoBehaviour {

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

    [SerializeField] Sprite m_closedSprite;
	[SerializeField] Sprite m_openSprite;
[SerializeField] AudioCue m_doorsound = null;

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

    SpriteRenderer m_spriteRenderer = null;
    
    // Public methods 
    //--------------------------------

    public bool IsOpen()
    {
        CarryTarget[] carryTargets = FindObjectsOfType<CarryTarget>();
        foreach (var eachCarryTarget in carryTargets)
        {
            if (!eachCarryTarget.IsFilled())
            {
                return false;
            }
        }

        return true;
    }
    
    // Private methods 
    //--------------------------------

    void Awake()
    {
        m_spriteRenderer = GetComponent<SpriteRenderer>();
    }
    void Start()
	{
		m_wasOpen = true;
        CarryTarget[] carryTargets = FindObjectsOfType<CarryTarget>();
        foreach (var eachCarryTarget in carryTargets)
		{
            if (!eachCarryTarget.IsFilled())
            {
				m_wasOpen = false;
            }

        }
    }
   	bool m_wasOpen = false;
    void Update () 
    {
        bool open = true;
        CarryTarget[] carryTargets = FindObjectsOfType<CarryTarget>();
        foreach (var eachCarryTarget in carryTargets)
        {
            if (!eachCarryTarget.IsFilled())
            {
                open = false;
            }
        }

        if (open)
        {
            m_spriteRenderer.sprite = m_openSprite;
        }
        else
        {
            m_spriteRenderer.sprite = m_closedSprite;
        }

		if ( open && m_wasOpen == false )
		{
			SystemAudio.Play(			m_doorsound);
			m_wasOpen = true;
		}
    }
}