using Cirno.Scripts.Components.Actors;
using Cirno.Scripts.Enums;
using Godot;

namespace Cirno.Scripts.Components.FSM.Enemy;

public partial class EnemyKnockbackProvider : ModuleBase<EnemyState, CharacterBody2D>
{
    [Export] public GenericDamageReceiver DamageReceiver { get; private set; }
    [Export] public EnemyStorageModule StorageModule { get; private set; }
    
    [Export] public float KnockbackDecayRate = 800f; // pixels per second^2, tweak this

    private Vector2 KnockbackVelocity
    {
        get => StorageModule.KnockbackVelocity;
        set => StorageModule.KnockbackVelocity = value;
    }

    private bool IsKnockbackActive => KnockbackVelocity.LengthSquared() > 1f;
    
    private IStateMachine<EnemyState, CharacterBody2D> _machine;
    private bool _enabled = false;
    public override void EnterState(EnemyState state)
    {
        _enabled = true;
        DamageReceiver.BulletHit += DamageReceiverOnBulletHit;
    }

    private void DamageReceiverOnBulletHit(Bullet bullet, Vector2 position, Vector2 direction)
    {
        var knockbackVelocity = direction * bullet.BulletInfo.Knockback;
        
        KnockbackVelocity = knockbackVelocity;
    }

    public override void ExitState(EnemyState state)
    {
        _enabled = false;
        DamageReceiver.BulletHit -= DamageReceiverOnBulletHit;
    }

    public override void Init(IStateMachine<EnemyState, CharacterBody2D> machine)
    {
        _machine = machine;
    }

    public override void Process(double delta)
    {
        
    }

    public override void PhysicsProcess(double delta)
    {
        if (IsKnockbackActive)
        {
            KnockbackVelocity = KnockbackVelocity.MoveToward(Vector2.Zero, KnockbackDecayRate * (float)delta);
        }
    }
}