using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Events;

[RequireComponent(typeof(Collider))]
public class Projectile : MonoBehaviour
{
    [SerializeField, Range(0f, 1f)]
    private float bounciness = 0.5f;

    private Collider projCol;
    private Rigidbody body;

    [SerializeField, Range(-50, 50)]
    private int damage = 10;

    [SerializeField]
    private int wallRebounces = 4;
    private int hitWalls = 0;

    public HealthComponent comingFrom;

    public UnityEvent OnReflect;

    private Vector3 prevVel;

    [SerializeField] ParticleSystem splashPS;

    private void Awake()
    {
        projCol = GetComponent<Collider>();
        body = GetComponent<Rigidbody>();
        Assert.IsNotNull(projCol);

        PhysicMaterial pMat = new();
        pMat.bounciness = this.bounciness;
        pMat.staticFriction = 0f;
        pMat.dynamicFriction = 0f;
        pMat.frictionCombine = PhysicMaterialCombine.Minimum;
        pMat.bounceCombine = PhysicMaterialCombine.Minimum;

        projCol.material = pMat;
    }

    void Start()
    {
        if (splashPS != null)
        {
            splashPS.time = 0f;
            splashPS.Play();
        }
    }

    private void LateUpdate()
    {
        prevVel = body.velocity;
    }

    private void OnCollisionEnter(Collision collision)
    {
        HealthComponent hitHealthComp = collision.gameObject.GetComponent<HealthComponent>();
        if (hitHealthComp == null)
            hitHealthComp = collision.transform.parent.GetComponent<HealthComponent>();
        // if (hitHealthComp == comingFrom) return;
        if (hitHealthComp)
        {
            hitHealthComp.TakeDamage(damage);
            Destroy(gameObject);
        }
        else
        {
            if (++hitWalls == wallRebounces)
            {
                Destroy(gameObject);
            }
            Vector3 newVel = Vector3.Reflect(prevVel.normalized, collision.contacts[0].normal.normalized);
            body.velocity = newVel.normalized * prevVel.magnitude * bounciness;
            OnReflect?.Invoke();
            AudioManager.PlaySound("BulletBounce", transform.position);

            if (splashPS != null)
            {
                splashPS.time = 0f;
                splashPS.Play();
            }
        }
    }
}