using MonoGame.FourEngine.Resources;
using Microsoft.Xna.Framework;

namespace MonoGame.FourEngine.Components
{
    public class TextComponent : Component
    {
        public Font Font { get; }
        public Point Frame { get; set; }
        public string Text { get; set; }
        public Color Color { get; set; } = Color.White;
        public int Width => Font.MeasureText(Text);
        public int Height => Font.Size.Y;
        
        public event TextDrawHandler BeforeDraw;

        public TextComponent(FontDefinition def)
        {
            ServiceLocator.ResourceManager.Add(ResourceTypes.Font, def);
            if (!string.IsNullOrEmpty(def?.FileName))
                Font = ServiceLocator.ResourceManager.Get<Font>(def.FileName);
        }

        public bool Contains(Point point)
        {
            if (point.X < Position.X) return false;
            if (point.Y < Position.Y) return false;
            if (point.X > Position.X + Width) return false;
            if (point.Y > Position.Y + Height) return false;
            return true;
        }

        public override void OnDraw(DrawEventArgs args)
        {
            base.OnDraw(args);
            if (Font == null || string.IsNullOrWhiteSpace(Text)) return;

            var textArgs = new TextDrawEventArgs(this)
            {
                Position = Position,
                Text = Text,
                Color = Color
            };

            BeforeDraw?.Invoke(textArgs);

            Font.DrawText(
                args.Batch, 
                textArgs.Text,
                textArgs.Position,
                textArgs.Color);
        }
    }
}