using Godot;
using System.Collections.Generic;
using Cirno.Scripts.Actors;
using Cirno.Scripts.AttackPatterns;
using Godot.Collections;

namespace Cirno.Scripts.Resources;

[GlobalClass]
[Tool]
public partial class PatternGroup : AttackPattern
{
    [Export] private Array<AttackPattern> patterns;
    
    public override IPatternMachine MakeMachine(Node parent)
    {
        return new PatternGroupMachine(this, parent);
    }

    public class PatternGroupMachine(PatternGroup patternGroup, Node parent) : IPatternMachine
    {
        public Node Parent => parent;
        private int _currentPatternIndex = 0;
        
        private AttackPattern CurrentPattern => patternGroup.patterns[_currentPatternIndex];
        
        IPatternMachine _patternMachine;
        
        public void Start()
        {
            _currentPatternIndex = 0;
            _patternMachine = CurrentPattern.MakeMachine(parent);
            _patternMachine.Start();
        }

        public void UpdatePattern(double delta)
        {
            if (_currentPatternIndex < patternGroup.patterns.Count)
            {
                _patternMachine.UpdatePattern(delta);
                
                if (!CurrentPattern.WaitForCompletion || _patternMachine.IsComplete())
                {
                    _currentPatternIndex++;
                    if (_currentPatternIndex < patternGroup.patterns.Count)
                    {
                        _patternMachine = CurrentPattern.MakeMachine(parent);
                        _patternMachine.Start();
                    }
                }
            }
        }

        public bool IsComplete()
        {
            return _currentPatternIndex >= patternGroup.patterns.Count;
        }
        
    }
}
