using System.Collections;
using Boxes;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Box : MonoBehaviour
{
    public BoxData boxData;
    private Coroutine _lifetimeCoroutine;

    public void Init(BoxData data)
    {
        boxData = data;
        if (_lifetimeCoroutine != null) StopCoroutine(_lifetimeCoroutine);
        _lifetimeCoroutine = StartCoroutine(LifetimeRoutine());
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            if (boxData != null)
            {
                GameEvents.OnBoxCollected?.Invoke(boxData);
            }
            CollectAndReturn();
        }
    }

    IEnumerator LifetimeRoutine()
    {
        yield return new WaitForSeconds(15f);
        CollectAndReturn();
    }

    private void CollectAndReturn()
    {
        if (_lifetimeCoroutine != null) StopCoroutine(_lifetimeCoroutine);
        
        if (boxData != null && boxData.boxPrefab != null)
        {
            SimpleObjectPool.Instance.ReturnToPool(boxData.boxPrefab, gameObject);
        }
    }
}