using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;

namespace MonoGame.FourEngine.Components
{
    public partial class AnimationComponent : Component
    {
        public event EventHandler AnimationCompleted;

        private Animation _animation;
        private SpriteComponent _spriteComponent;
        private IEnumerator<Point> _animationEnumerator;

        public bool IsRunning => _animation != null;

        public AnimationComponent(SpriteComponent spriteComponent)
        {
            _spriteComponent = spriteComponent;
        }

        public void StartAnimation(Animation animation)
        {
            _animation = animation;
            _animationEnumerator = animation.GetEnumerator();
        }

        public void StopAnimation()
        {
            _animation = null;
            _animationEnumerator = null;
        }

        public override void OnUpdate(UpdateEventArgs args)
        {
            base.OnUpdate(args);
            if (_animation == null || _animationEnumerator == null) return;
            _spriteComponent.Frame = _animationEnumerator.Current;
            _animation.Update(args);
            if (!_animationEnumerator.MoveNext())
            {
                StopAnimation();
                AnimationCompleted?.Invoke(this, null);
            }
        }
    }
}