using UnityEngine;
using System.Collections.Generic;

public class ButtonController : MonoBehaviour
{
    public Sprite deactivatedSprite;
    public Sprite activatedSprite;

    private SpriteRenderer sprite_renderer;
    private HashSet<Collider2D> activators = new HashSet<Collider2D>();

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        this.sprite_renderer = GetComponent<SpriteRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
 
    }

    private bool IsValidActivator(Collider2D collision)
    {
        // Check if it's a box
        if (collision.GetComponent<BoxController>() != null)
            return true;

        // Check if it's a player with button activation ability
        PlayerController player = collision.GetComponent<PlayerController>();
        if (player != null && player.canActivateButton)
            return true;

        return false;
    }

    private void UpdateButtonState()
    {
        if (activators.Count > 0)
        {
            this.sprite_renderer.sprite = this.activatedSprite;
        }
        else
        {
            this.sprite_renderer.sprite = this.deactivatedSprite;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (IsValidActivator(collision))
        {
            activators.Add(collision);
            UpdateButtonState();
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (activators.Remove(collision))
        {
            UpdateButtonState();
        }
    }

    public bool isActive()
    {
        return activators.Count > 0;
    }
}
