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

namespace Cirno.Scripts.Resources.ScriptableBullets;

[GlobalClass]
[Tool]
public partial class ParallelPatternGroup : AttackPattern
{
    [Export(PropertyHint.None, "suffix:s")] public float Duration { get; private set; } = 10f;
    [Export] public Array<AttackPattern> Patterns { get; private set; } = [];
    
    public override IPatternMachine MakeMachine(Node parent)
    {
        return new ParallelPatternGroupMachine(this, parent);
    }

    public class ParallelPatternGroupMachine(ParallelPatternGroup patternGroup, Node parent) : IPatternMachine
    {
        public Node Parent => parent;
        //private int _currentPatternIndex = 0;
        
        //private AttackPattern CurrentPattern => patternGroup.Patterns[_currentPatternIndex];

        private double _progressTimer = 0;
        
        private List<IPatternMachine> _patternMachines = [];
        
        public void Start()
        {
            //_currentPatternIndex = 0;
            foreach (var pattern in patternGroup.Patterns)
            {
                var machine = pattern.MakeMachine(parent);
                _patternMachines.Add(machine);
                machine.Start();
            }
        }

        public void UpdatePattern(double delta)
        {
            _progressTimer += delta;
            foreach (var patternMachine in _patternMachines)
            {
                //if (!CurrentPattern.WaitForCompletion || _patternMachine.IsComplete())
                if (patternMachine.IsComplete()) continue;
                patternMachine.UpdatePattern(delta);
            }
           
        }

        public bool IsComplete()
        {
            if (patternGroup.WaitForCompletion)
            {
                return _patternMachines.TrueForAll(x => x.IsComplete()) && _progressTimer >= patternGroup.Duration;
            }

            return _patternMachines.TrueForAll(x => x.IsComplete()) || _progressTimer >= patternGroup.Duration;

        }
        
    }
}
