using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;

namespace Ika.Graphics
{
    /// <summary>
    /// Represents an animated sprite using a Sprite sheet
    /// </summary>
    public class AnimatedSprite : SpriteSheet
    {
        int m_frameTime;
        /// <summary>
        /// The length between two animation step, in milliseconds
        /// </summary>
        public int FrameTime
        {
            get { return m_frameTime; }
            set { m_frameTime = value; SpriteFromTime(); }
        }

        bool m_loop = true;
        /// <summary>
        /// Does the animation loop when finished
        /// </summary>
        public bool Loop
        {
            get { return m_loop; }
            set { m_loop = value; }
        }

        int m_totalTime;
        /// <summary>
        /// The current time of the animation, in milliseconds
        /// </summary>
        public int AnimationTime
        {
            get { return m_totalTime; }
            set { m_totalTime = value; SpriteFromTime(); }
        }

        /// <summary>
        /// Create a AnimatedSprite
        /// </summary>
        /// <param name="texture">The texture containing the Sprite sheet</param>
        /// <param name="size">The world size of the sprite</param>
        /// <param name="totalStotalSpritesteps">The number of sprite locations in the source texture</param>
        /// <param name="usedSprites">The number of sprite locations actually used</param>
        /// <param name="frameTime">The length between two animation step, in milliseconds</param>
        public AnimatedSprite(Texture2D texture, Vector2 size, int totalSprites, int usedSprites, int frameTime)
        : base(texture, size, totalSprites, usedSprites)
        {
            m_frameTime = frameTime;
        }

        /// <summary>
        /// Move the animation forward
        /// </summary>
        /// <param name="time">The time to add to the animation</param>
        public void AddTime(TimeSpan time)
        {
            AnimationTime += (int)time.TotalMilliseconds;
        }

        protected void SpriteFromTime()
        {
            int totalTimeToSprite = m_totalTime / m_frameTime;
            int spriteIndex = totalTimeToSprite % m_usedSprites;
            if (Loop || totalTimeToSprite < m_usedSprites)
            {
                SetSprite(spriteIndex);
            }
            else
            {
                SetSprite(m_usedSprites - 1);
            }
        }
    }
}
