using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MonoGame.FourEngine.Components
{
    public class DrawingSurfaceComponent : Component, IDrawableComponent
    {
        public DrawingSurfaceBase DrawingSurface { get; }
        public int Width => DrawingSurface.Target.Width;
        public int Height => DrawingSurface.Target.Height;
        public SpriteDrawEventArgs DrawArgs { get ; protected set; }
        public bool ManipulationEnabled { get; set; }

        public event SpriteDrawHandler BeforeDraw;

        public DrawingSurfaceComponent(DrawingSurfaceBase target)
        {
            DrawingSurface = target;
        }

        public override void OnUpdate(UpdateEventArgs args)
        {
            base.OnUpdate(args);
            DrawingSurface.Update(args);
        }

        public override void OnDraw(DrawEventArgs args)
        {
            base.OnDraw(args);
            if (DrawingSurface.Target == null) return;

            var drawArgs = new SpriteDrawEventArgs(this)
            {
                DestinationRectangle = new Rectangle(
                    Position.X, Position.Y,
                    Width, Height),
                SourceRectangle = DrawingSurface.Target.Bounds,
                Color = Color.White,
                SpriteEffects = SpriteEffects.None
            };

            BeforeDraw?.Invoke(drawArgs);

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