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

namespace MonoGame.FourEngine.Components
{
    public class SpriteComponent : Component, IDrawableComponent
    {
        public Sprite Sprite { get; }
        public Point Frame { get; set; }
        public Color Color { get; set; } = Color.White;
        public int Width => Sprite.Size.X;
        public int Height => Sprite.Size.Y;
        public SpriteDrawEventArgs DrawArgs { get; protected set; }
        public bool ManipulationEnabled { get; set; }

        public Point FrameCount => Sprite.FrameCount;

        public event SpriteDrawHandler BeforeDraw;

        public SpriteComponent(SpriteDefinition def)
        {
            if (def == null) return;
            ServiceLocator.ResourceManager.Add(ResourceTypes.Sprite, def);
            if (!string.IsNullOrEmpty(def?.FileName))
                Sprite = ServiceLocator.ResourceManager.Get<Sprite>(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 (Sprite == null) return;

            var drawArgs = Sprite[Frame].CreateDrawArgs(Position, Color);

            OnBeforeDraw(drawArgs);

            DrawArgs = drawArgs;
            args.Batch.Draw(
                Sprite.Texture,
                drawArgs.DestinationRectangle,
                drawArgs.SourceRectangle,
                drawArgs.Color,
                drawArgs.Rotation,
                drawArgs.Origin,
                drawArgs.SpriteEffects,
                0);
        }

        protected virtual void OnBeforeDraw(SpriteDrawEventArgs args)
        {
            BeforeDraw?.Invoke(args);
        }
    }
}