using System;
using Cybe;
using UniRx;
using UnityEngine;
using Zenject;

namespace Sources
{
    public class Sword : MonoBehaviour
    {
        [SerializeField] private Transform _owner;
        [SerializeField] private float _attackDuration = 1;
        [SerializeField] private GameObject _attackEffect;

        [Inject] private AudioManager _audioManager;
        [Inject] private Player _player;

        private float _currentDamage;
        private bool _isAttacking;
        private bool _isCooldown;

        public void SubscribeDamage(ReactiveProperty<int> damage)
        {
            damage.ObserveEveryValueChanged(v => v.Value)
                .Subscribe(value => _currentDamage = (40 + 10 * _player.CurrentLevel) * Mathf.Pow(1.3f, value));
        }
        
        public void StartAttack()
        {
            _isAttacking = true;
            _isCooldown = false;
            _audioManager.PlayFx(SoundType.SwordSwoosh);
            Observable.Timer(TimeSpan.FromSeconds(_attackDuration)).Subscribe(_ => _isAttacking = false);
        }
        
        private void OnTriggerStay(Collider other)
        {
            if (!_isAttacking || _isCooldown)
                return;
            
            var damageable = other.GetComponentInParent<IDamageable>();
            if (damageable == null)
                return;

            _isCooldown = true;
            
            _audioManager.PlayFx(SoundType.SwordHit);

            var hitPoint = other.ClosestPointOnBounds(transform.position);
            var effect = Instantiate(_attackEffect, hitPoint, Quaternion.identity, transform);
            Destroy(effect, 3f);

            damageable.TakeDamage(_currentDamage, _owner);
        }
    }
}