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

namespace GhostArena3D
{
    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;
        
        private Vector2 pos;
        
        public FrameRateCounter(Game game, Vector2 origin) : base(game)
        {
            _content = new ContentManager(game.Services);
            pos = origin;
        }

        protected override void LoadContent()
        {
             IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)this.Game.Services.GetService(typeof(IGraphicsDeviceService));

             _sb = new SpriteBatch(graphicsService.GraphicsDevice);
             _font = _content.Load<SpriteFont>("Content/Fonts/data");
        }
        
        protected override void UnloadContent()
        {
            _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(), pos, Color.White);
            _sb.End();

        }
    }
}
