using GatherAndDefend.Events;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[RequireComponent(typeof(Button))]
public abstract class PlacementButton : MonoBehaviour, IPointerDownHandler
{
    private bool _canUse = false;
    private Button _button;
    private DraggablePlaceholder _placeholder;
    [SerializeField]
    private Material _outlineMaterial;

    public bool CanUse => _canUse;
    public Button Button => _button;
    public DraggablePlaceholder Placeholder => _placeholder;
    public Material OutlineMaterial => _outlineMaterial;
    protected virtual void Start()
    {
        _button = GetComponent<Button>();
        _button.enabled = false;
        EventAggregator.Instance.GetEvent<LevelLoadedEvent>().Attach(OnLevelLoaded);
        EventAggregator.Instance.GetEvent<ExitingLevelEvent>().Attach(DeactivateButton);
    }

    protected virtual void Update()
    {
        _button.interactable = CanPlace();
    }

    private void OnLevelLoaded(GatherAndDefend.LevelEditor.Level level)
    {
        _canUse = true;
        EventAggregator.Instance.GetEvent<LevelLoadedEvent>().Detach(OnLevelLoaded);
    }

    void DeactivateButton()
    {
        EventAggregator.Instance.GetEvent<ExitingLevelEvent>().Detach(DeactivateButton);
        _canUse = false;
    }
    public virtual void OnPointerDown(PointerEventData eventData)
    {
        if (!_button.interactable) return;
        _placeholder = Place();
    }
    protected abstract DraggablePlaceholder Place();
    protected virtual bool CanPlace()
    {
        return Button.enabled && CanUse;
    }
}