using UnityEngine;
using System.Collections;

public class DoorKnob : MonoBehaviour
{
    public GameObject promptBeforeOpen;
    public GameObject promptDoorKnob;
    public GameObject door; 
    private AudioSource audioSource;
    bool isBeingDestroyed = false;

    void Awake()
    {
        audioSource = GetComponent<AudioSource>();
    }

    private void OnMouseEnter()
    {
        if (!UIManagerIntro.Instance.GetIsPaused() && !isBeingDestroyed)
        {
            if (door)
                door.GetComponent<BoxCollider2D>().enabled = false;
            if (promptBeforeOpen)
                promptBeforeOpen.SetActive(false);
            if (promptDoorKnob)
                promptDoorKnob.SetActive(true);
        }
    }

    private void OnMouseExit()
    {
        if (!UIManagerIntro.Instance.GetIsPaused() && !isBeingDestroyed)
        {
            if (door)
                door.GetComponent<BoxCollider2D>().enabled = true;
            if (promptDoorKnob)
                promptDoorKnob.SetActive(false);
        }
    }

    private void OnMouseDown()
    {
        if (!UIManagerIntro.Instance.GetIsPaused() && !isBeingDestroyed)
        {
            door.GetComponent<IntroDoor>().SetOpen(true);

            if (audioSource)
                audioSource.Play();

            if (promptDoorKnob)
                promptDoorKnob.SetActive(false);

            StartCoroutine(WaitForSoundAndDestroy());
        }
    }

    private IEnumerator WaitForSoundAndDestroy()
    {
        while (audioSource.isPlaying)
            yield return null;

        if (door)
            door.GetComponent<BoxCollider2D>().enabled = true;

        Destroy(gameObject);
    }
}
