using System;
using UnityEngine;

public interface MagnetInterface
{
    void Attract(GameObject obj);
    void Release(GameObject obj);
}

public class MagnetComponent : MonoBehaviour
{
    public event Action<float> OnGetExp;
    
    private MagnetTrigger _spotTrigger;
    private MagnetTrigger _rangeTrigger;
    
    void Awake()
    {
        GameObject spot = this.transform.Find("Spot").gameObject;
        GameObject range = this.transform.Find("Range").gameObject;
        
        if (spot != null)
        {
            _spotTrigger = spot.GetComponent<MagnetTrigger>();
            _spotTrigger.OnTrigger -= HandleSpotTrigger;
            _spotTrigger.OnTrigger += HandleSpotTrigger;
        }

        if (range != null)
        {
            _rangeTrigger = range.GetComponent<MagnetTrigger>();
            _rangeTrigger.OnTrigger -= HandleRangeTrigger;
            _rangeTrigger.OnTrigger += HandleRangeTrigger;
        }
    }
    

    private void HandleSpotTrigger(Collider other)
    {
        if (other.gameObject.layer == LayerMask.NameToLayer("Object"))
        {
            Debug.Log("Spot: " + other.name);
            ExpCubeComponent expCube = other.GetComponent<ExpCubeComponent>();
            if (expCube != null)
            {
                OnGetExp?.Invoke(expCube.ExpAmount);
                Destroy(other.gameObject);
            }
            
        }
    }

    private void HandleRangeTrigger(Collider other)
    {
        if (other.gameObject.layer == LayerMask.NameToLayer("Object"))
        {
            Debug.Log("Range: " + other.name);
            ExpCubeComponent expCube = other.GetComponent<ExpCubeComponent>();
            if (expCube != null) expCube.Attract(this.transform.parent);
        }
    }


}
