using System;
using System.Collections.Generic;
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.Components
{
    public interface IFramerateService
    {
        int Framerate
        {
            get;
        }
    }

    public class FramerateComponent : Microsoft.Xna.Framework.DrawableGameComponent, IFramerateService
    {
        SpriteBatch m_spriteBatch;
        SpriteFont m_spriteFont;
        Vector2 m_position;

        int NB_FRAME_SAMPLE = 20;
        int m_currentFrame;

        TimeSpan m_referenceTime;

        int m_framerate;

        public int Framerate
        {
            get
            {
                return m_framerate;
            }
        }

        public FramerateComponent(Game game)
            : base(game)
        {
            m_currentFrame = 0;
            m_framerate = 0;
            m_position = new Vector2(5.0f, 5.0f);
            Game.Services.AddService(typeof(FramerateComponent), this);
        }

        public FramerateComponent(Game game, Vector2 position)
            : base(game)
        {
            m_currentFrame = 0;
            m_framerate = 0;
            m_position = position;
        }

        public override void Initialize()
        {
            m_spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            m_spriteFont = Game.Content.Load<SpriteFont>("fpsFont");
            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            m_currentFrame++;
            if (m_currentFrame == NB_FRAME_SAMPLE)
            {
                int frameTime = (int)(gameTime.TotalRealTime.TotalMilliseconds - m_referenceTime.TotalMilliseconds);
                m_framerate = (int)((float)NB_FRAME_SAMPLE / (float)frameTime * 1000);

                m_referenceTime = gameTime.TotalRealTime;
                m_currentFrame = 0;
            }

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            m_spriteBatch.Begin(SpriteBlendMode.Additive, SpriteSortMode.Immediate, SaveStateMode.SaveState);
            m_spriteBatch.DrawString(m_spriteFont, "Framerate: " + this.Framerate, m_position, Color.White);
            m_spriteBatch.End();

            base.Update(gameTime);
        }
    }
}