using System;
using UniRx;
using UnityEngine;

namespace Sources
{
    public class Bullet : MonoBehaviour
    {
        [SerializeField] private Rigidbody _rb;
        [SerializeField] private float _flySpeed = 100f;
        [SerializeField] private GameObject _destroyEffect;

        private float _damage;
        private Transform _owner;
        private IDisposable _lifetimeTimer;
        
        private void Awake()
        {
            _destroyEffect.SetActive(false);
        }

        public void Shoot(float damage, Vector3 direction, Transform owner, float speed = 0)
        {
            _damage = damage;
            _owner = owner;
            var sendSpeed = speed > 0 ? speed : _flySpeed;
            _rb.AddForce(direction.normalized * sendSpeed);
            _lifetimeTimer = Observable.Timer(TimeSpan.FromSeconds(10)).Subscribe(_ => Destroy(gameObject));
        }

        private void OnTriggerEnter(Collider other)
        {
            var damageable = other.GetComponentInParent<IDamageable>();
            if (damageable == null)
            {
                Die();
                return;
            }
            
            damageable.TakeDamage(_damage, _owner, DamageType.Ranged);
            Die();
        }

        private void Die()
        {
            _lifetimeTimer?.Dispose();
            _rb.constraints = RigidbodyConstraints.FreezeAll;
            _destroyEffect.SetActive(true);
            Destroy(gameObject, 2f);
        }
    }
}