using System.Linq;
using Cirno.Scripts.AttackPatterns;
using Godot;
using Godot.Collections;

namespace Cirno.Scripts.Resources;

[GlobalClass]
[Tool]
public partial class BulletScript : Resource
{
    [Export]
    public Array<AttackPattern> Patterns { get; private set; }
    
    public BulletScriptMachine Make(Node2D parent)
    {
        return new BulletScriptMachine(parent, Patterns);
    }
    
    public class BulletScriptMachine(Node2D parent, Array<AttackPattern> patterns)
    {
        private int _currentPatternIndex = 0;
        //private double _patternTimer;
    
        private AttackPattern CurrentPattern => patterns[_currentPatternIndex];

        private IPatternMachine _currentPatternMachine;
        
        public void Start()
        {
            if (patterns.Count == 0) return;
            _currentPatternIndex = 0;

            _currentPatternMachine = CurrentPattern.MakeMachine(parent);
            _currentPatternMachine.Start();
        }
    
        public void UpdatePhase(double delta)
        {
            //_patternTimer += delta;
            
            _currentPatternMachine.UpdatePattern(delta);
            //CurrentPattern.UpdatePattern(delta);

            if (!CurrentPattern.WaitForCompletion || _currentPatternMachine.IsComplete())
            {
                _currentPatternIndex = (_currentPatternIndex + 1) % patterns.Count;
                _currentPatternMachine = CurrentPattern.MakeMachine(parent);
                _currentPatternMachine.Start();
            }
        }
    }
}