using Godot;

namespace Cirno.Scripts.Actors;

public partial class Prism : Area2D
{
    [Export] public float ReflectionAngle { get; private set; } = 90f;
    [Export] public float RotationSpeed { get; set; } = 0f;

    private Sprite2D _sprite;

    [Export] public float[] Angles { get; set; } = [-90f, -45f, 180f, 45f, 90f];
    
    private int _angleIndex = 0;

    private double _rotateTimer = 0;
    
    public override void _Ready()
    {
        this.AreaEntered += OnCollision;
        _sprite = this.GetNode<Sprite2D>("Sprite2D");

        SetReflectionAngle(ReflectionAngle);
        
    }

    public override void _PhysicsProcess(double delta)
    {
        if (RotationSpeed > 0)
        {
            _rotateTimer += delta;
        }
        
        if (_rotateTimer > RotationSpeed)
        {
            _rotateTimer = 0;
            _angleIndex++;
            if (_angleIndex >= Angles.Length)
            {
                _angleIndex = 0;
            }
            //var angleDifference = (float)(RotationSpeed * delta);
            //var newAngle = ReflectionAngle + angleDifference;
            // if (newAngle > 360)
            // {
            //     newAngle = 0;
            //     
            // }
            var newAngle = Angles[_angleIndex];
            SetReflectionAngle(newAngle);
        }
    }

    public void SetReflectionAngle(float angle)
    {
        ReflectionAngle = angle;
        var frames = _sprite.Hframes;
        var frame = (int)(frames * angle / 360);

        _sprite.SetFrame(Mathf.Clamp(frame -1, 0, _sprite.Hframes) );
    }
    
    private void OnCollision(Area2D other)
    {
        if (other is not Bullet bullet) return;
        
        bullet.RotateBullet(ReflectionAngle);
    }
    
}