using UnityEngine;
using static UnityEngine.ParticleSystem;

[CreateAssetMenu(fileName = "bullet_effect_controller", menuName = "Bullet effect Controller")]
public sealed class BulletEffectController : ScriptableObject
{
    [SerializeField]
    private ParticleSystem particleSystemPrefab = null;
    [SerializeField]
    private float gravitySpeed = 1f;
    [SerializeField]
    private float additionalLifeTime = 0f;

    private ParticleSystem particleSystem = null;
    private ParticleSystem ParticleSystem {
        get {
            if (particleSystem == null)
                particleSystem = CreateItem(particleSystemPrefab);
            return particleSystem;
        }
    }

    public void Fire(Vector3 from, Vector3 to, float speed) {
        var delta = to - from;
        var direction = delta.normalized;
        var distance = Vector3.Distance(from, to);
        var flyTime = (distance / speed);
        var effectParams = new EmitParams()
        {
            position = from,
            velocity = direction * speed + Vector3.up * (gravitySpeed * flyTime),
            startLifetime = distance / speed + additionalLifeTime
        };
        ParticleSystem.Emit(effectParams, 1);
    }

    private T CreateItem<T>(T prefab) where T: Component
    {
        var item = Instantiate(prefab);
        DontDestroyOnLoad(item.gameObject);
        return item;
    }
}
