using Godot;
using System;

namespace Cirno.Scripts.Components.Actors;
public partial class TurretAnimationModule : ActorModule
{
    [Export] public AnimatedSprite2D TurretSprite;
    [Export(PropertyHint.None, "suffix:°")] public float SweepAngle = 360f;
    [Export(PropertyHint.None, "suffix:°")] public float RotationOffset = 0f;
    [Export]
    public bool InvertRotation = false;
    
    private int _frameCount;
    private float _anglePerFrame;
    
    private Actor _actor;
    
    public override void Init(Actor actor)
    {
        _actor = actor;
        if (TurretSprite == null)
        {
            GD.PushError("TurretAnimationModule requires an AnimatedSprite2D reference.");
            return;
        }
        
        _frameCount = TurretSprite.SpriteFrames.GetFrameCount(TurretSprite.Animation);
        if (_frameCount == 0)
        {
            GD.PushError("TurretAnimatedSprite2D has no frames in the selected animation.");
            return;
        }
        
        _anglePerFrame = SweepAngle / _frameCount;
    }
    
    public override void Update(double delta) { }
    
    public override void PhysicsUpdate(double delta)
    {
        if (TurretSprite == null || _frameCount == 0) return;

        Vector2 facingDirection = _actor.FacingDirection;
        float angle = Mathf.RadToDeg(facingDirection.Angle()) + RotationOffset;
        
        if (InvertRotation)
        {
            angle = -angle;
        }
        
        if (SweepAngle < 360f)
        {
            angle = Mathf.Clamp(angle, -SweepAngle / 2, SweepAngle / 2);
        }
        
        int frame = Mathf.Wrap((int)Mathf.Round(angle / _anglePerFrame), 0, _frameCount);
        TurretSprite.Frame = frame;
    }
}
