using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;

public class PlayerParticles : MonoBehaviour
{
    Battler _battler;

    void Awake()
    {
        _battler = GetComponent<Battler>();
        _battler.TookHit += ShowHitParticle;
        _battler.Died += ShowDeathParticle;
    }

    void ShowDeathParticle() => StartCoroutine(ShowDeathParticleDelayed());

    IEnumerator ShowDeathParticleDelayed()
    {
        yield return new WaitForSeconds(BattleManager.Settings.DeadBodyRemainsDuration);
        var prefab = ChooseRandom(BattleManager.Settings.DeathParticles);
        if (prefab != null)
            SpawnParticle(prefab);
    }

    void ShowHitParticle(int damage, bool wasCrit)
    {
        var prefab = ChooseRandom(BattleManager.Settings.HitParticles);
        if (prefab != null)
            SpawnParticle(prefab);
    }

    ParticleSystem ChooseRandom(List<ParticleSystem> systems) =>
        systems?.Count > 0 ? systems[Random.Range(0, systems.Count)] : null;


    void SpawnParticle(ParticleSystem prefab)
    {
        var particle = Instantiate(prefab, transform.position + transform.up + (transform.forward * 0.5f), Quaternion.identity);
        particle.Play();
        Destroy(particle.gameObject, 3f);
    }
}