using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace GhostArena3
{
    public class FrameRateCounter : DrawableGameComponent
    {
        private ContentManager _content;
        private SpriteBatch _sb;
        private SpriteFont _font;

        private int _framerate = 0;
        private int _counter = 0;

        private float _elapsedTime = 0.0f;
        
        public FrameRateCounter(Game game)
            : base(game)
        {
            _content = new ContentManager(game.Services);
        }

        protected override void LoadGraphicsContent(bool loadAllContent)
        {
            if (loadAllContent)
            {
                IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)this.Game.Services.GetService(typeof(IGraphicsDeviceService));

                _sb = new SpriteBatch(graphicsService.GraphicsDevice);
                _font = _content.Load<SpriteFont>("Content/data");
            }
        }
        
        protected override void UnloadGraphicsContent(bool unloadAllContent)
        {
            if (unloadAllContent)
                _content.Unload();
        }
        
        public override void Update(GameTime gameTime)
        {
            _elapsedTime += gameTime.ElapsedGameTime.Milliseconds;

            if (_elapsedTime >= 1000.0f)
            {
                _elapsedTime -= 1000.0f;
                _framerate = _counter;
                _counter = 0;
            }
        }


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

            _sb.Begin();
            _sb.DrawString(_font, "fps: " + _framerate.ToString(), new Vector2(32, 32), Color.White);
            _sb.End();

        }
    }
}
