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

public class Beacon : MonoBehaviour
{
    public int ActiveColorInt;
    public int InactiveColorInt;

    private Color _activeColor;
    private Color _inactiveColor;
    private bool isActivated = false;

    public ColourSampler _colourSampler;

    public UnityEvent OnActionChanged;

    public AudioClip activateSound;
    public AudioClip deactivateSound;

    private AudioSource source;

    public bool IsActivated
    {
        get { return isActivated; }
    }

    private void Awake()
    {
        source = this.GetComponent<AudioSource>();
        if (!_colourSampler)
        {
            _activeColor = Color.magenta;
            _inactiveColor = Color.magenta;
        }
        else
        {
            _activeColor = _colourSampler.GetColor(ActiveColorInt);
            _inactiveColor = _colourSampler.GetColor(InactiveColorInt);
        }

        gameObject.layer = LayerMask.NameToLayer("EndPoint");
        UpdateColor();
    }

    public void ToggleActivate(int col)
    {
        if (isActivated && col == InactiveColorInt)
        {
            isActivated = false;
            source.clip = deactivateSound;
            source.Play();
        }
        if (!isActivated && col == ActiveColorInt)
        {
            isActivated = true;
            source.clip = activateSound;
            source.Play();
        }
        UpdateColor();

        OnActionChanged.Invoke();
    }

    private void UpdateColor()
    {
        var list = GetComponentsInChildren<Renderer>();
        foreach (var l in list)
        {
            l.material.color = (!isActivated) ? _activeColor : _inactiveColor;
        }
    }
}