using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Trigger : MonoBehaviour {

    public GameObject interactableObj;
    public PlayerEnum triggerPlayer;
    public Color InactiveColor;
    public Color ActiveColor;

    private SpriteRenderer sr;
    private AudioSource audio;
    private IInteractable interactable;


    void Start()
    {
        sr = GetComponent<SpriteRenderer>();
        audio = GetComponent<AudioSource>();

        interactable = null;

        MonoBehaviour[] list = interactableObj.GetComponents<MonoBehaviour>();
        foreach (MonoBehaviour mb in list)
        {
            Debug.Log(mb.name);
            if (mb is IInteractable)
            {
                interactable = (IInteractable)mb;
                break;
            }
        }

    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (interactable == null) return;

        switch (triggerPlayer)
        {
            case PlayerEnum.Human:
                if (other.gameObject == LevelController.Instance.PlayerHuman)
                {
                    Activate();
                }
                break;
            case PlayerEnum.Ghost:
                if (other.gameObject == LevelController.Instance.PlayerGhost)
                {
                    Activate();
                }
                break;
            case PlayerEnum.Both:
                if (other.gameObject == LevelController.Instance.PlayerHuman || other.gameObject == LevelController.Instance.PlayerGhost)
                {
                    Activate();
                }
                break;
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (interactable == null) return;

        switch (triggerPlayer)
        {
            case PlayerEnum.Human:
                if (other.gameObject == LevelController.Instance.PlayerHuman)
                {
                    Deactivate();
                }
                break;
            case PlayerEnum.Ghost:
                if (other.gameObject == LevelController.Instance.PlayerGhost)
                {
                   Deactivate();
                }
                break;
            case PlayerEnum.Both:
                if (other.gameObject == LevelController.Instance.PlayerHuman || other.gameObject == LevelController.Instance.PlayerGhost)
                {
                    Deactivate();
                }
                break;
        }
    }

    private void Activate()
    {
        interactable.Activate();
        sr.color = ActiveColor;
        audio.Play();
    }

    private void Deactivate()
    {
        interactable.Deactivate();
        sr.color = InactiveColor;
    }
}
