using System;
using Grid;
using UnityEngine;
using Random = UnityEngine.Random;

public class Barrel : MonoBehaviour, IDestructable {
    [SerializeField] private Transform barrelDestroyedPrefab;

    private void Start() => GridPosition = LevelGrid.Instance.GetGridPosition(transform.position);
    public GridPosition GridPosition { get; set; }

    public void Damage(float damageAmount) {
        Transform barrelDestroyedTransform = Instantiate(barrelDestroyedPrefab, transform.position, transform.rotation);
        ApplyExplosionToChildren(barrelDestroyedTransform, Random.Range(damageAmount - 50f, damageAmount + 50f), transform.position, Random.Range(damageAmount / 10f, damageAmount / 5f));
        Destroy(gameObject);
        OnAnyDestroyed?.Invoke(this, EventArgs.Empty);
    }

    public static event EventHandler OnAnyDestroyed;

    private static void ApplyExplosionToChildren(Transform root, float explosionForce, Vector3 explosionPosition, float explosionRadius) {
        foreach (Transform child in root) {
            if (!child.TryGetComponent(out Rigidbody childRigidbody)) continue;
            childRigidbody.AddExplosionForce(explosionForce, explosionPosition, explosionRadius);
            ApplyExplosionToChildren(child, explosionForce, explosionPosition, explosionRadius);
        }
    }
}