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

namespace HiTest
{
    class FrameRateCounter : DrawableGameComponent
    {
        ContentManager content;
        SpriteBatch spriteBatch;
        SpriteFont spriteFont;

        int frameRate = 0;
        int frameCounter = 0;
        TimeSpan elapsedTime = TimeSpan.Zero;


        public FrameRateCounter(Game game)
            : base(game)
        {
            content = game.Content;
            x = game.GraphicsDevice.PresentationParameters.BackBufferWidth - 200;
        }

        private float x;


        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            spriteFont = content.Load<SpriteFont>("Standard");
        }

        public override void Update(GameTime gameTime)
        {
            elapsedTime += gameTime.ElapsedGameTime;

            if (elapsedTime > TimeSpan.FromSeconds(1))
            {
                // Calculate avg frame time
                int frames = Math.Min(frameCounter, samples.Length);
                float totalTime = 0;
                for (int i = 0; i < frames; i++)
                {
                    totalTime += samples[i];
                }
                float avgTime = totalTime / (float)frames;

                elapsedTime -= TimeSpan.FromSeconds(1);
                frameRate = frameCounter;
                fps = string.Format("fps: {0}", frameRate);
                timeEllapsed = string.Format("({0:0.0}ms)", avgTime * 1000f);
                frameCounter = 0;
            }
        }

        private string fps = string.Empty;
        private string timeEllapsed = string.Empty;

        private float[] samples = new float[200];

        public override void Draw(GameTime gameTime)
        {
            frameCounter++;

            if (frameCounter < samples.Length)
            {
                samples[frameCounter] = (float)gameTime.ElapsedGameTime.TotalSeconds;
            }

            spriteBatch.Begin();
            spriteBatch.DrawString(spriteFont, fps, new Vector2(x, 33), Color.Black);
            spriteBatch.DrawString(spriteFont, fps, new Vector2(x - 1, 32), Color.White);
            spriteBatch.DrawString(spriteFont, timeEllapsed, new Vector2(x, 53), Color.Black);
            spriteBatch.DrawString(spriteFont, timeEllapsed, new Vector2(x - 1, 52), Color.White);

            spriteBatch.End();
        }

    }
}
