using Igdc.Extensions;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using System.Linq;

namespace Igdc.Drawables
{
    public abstract class DrawableBase
    {
        public abstract Point Size { get; }
        public AnimationDefenition IdleAnimation { get; set; }
        public bool IdleAnimationEnabled { get; set; }

        private Stack<Point> _animationStack;
        private Point _lastFrame;
        private Point _previous;

        private bool _firstInterpolation = true;

        public Point Interpolate(Point location)
        {
            _previous = _previous.Interpolate(location, _firstInterpolation);
            _firstInterpolation = false;
            return _previous;
        }

        public void SetAnimation(AnimationDefenition def)
            => _animationStack = def.ToStack();
        
        public Point GetAnimationFrame()
        {
            if (_animationStack == null || !_animationStack.Any())
                if (IdleAnimationEnabled)
                    _animationStack = IdleAnimation?.ToStack();

            if (_animationStack == null || !_animationStack.Any())
                return _lastFrame;

            _lastFrame = _animationStack.Pop();
            return _lastFrame;
        }
    }

    public class AnimationDefenition : List<AnimationFrame>
    {
        public Stack<Point> ToStack()
        {
            var stack = new Stack<Point>();
            Reverse();
            foreach (var frame in this)
            {
                for (var i = 0; i < frame.Length; i++)
                    stack.Push(frame.Frame);
            }
            Reverse();
            return stack;
        }
    }

    public struct AnimationFrame
    {
        public Point Frame;
        public int Length;
    }
}