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

namespace MonoGame.FourEngine.Extensions
{
    internal static class PointerControlCopyExt
    {
        public static PointerControlCopy Apply (this PointerControlCopy control, SpriteDrawEventArgs args)
        {
            var canScale = args != null && args.DestinationRectangle.Size != args.SourceRectangle.Size;
            var canRotate = args?.Origin != null && args.Rotation != 0f;
            var canTranslate = args?.Origin != null;// && args.DestinationRectangle.Location != args.SourceRectangle.Location;

            if (!canScale && !canRotate && !canTranslate)
                return control;

            var position = control.Position;
            var center = args.DestinationRectangle.Location;

            if (canRotate)
            {
                // Rotate
                position = RotatePoint(position, center, -args.Rotation);
            }
            if (canScale)
            {
                // Scale
                var scale = args.DestinationRectangle.Size.ToVector2() / args.SourceRectangle.Size.ToVector2();
                position = ScalePoint(position, center, Vector2.One / scale);
            }
            if (canTranslate)
            {
                // Translate
                var location = args.DestinationRectangle.Location - args.Origin.ToPoint();
                control.Position = position - location;
            }

            return control;
        }

        private static Point ScalePoint(Point point, Point center, Vector2 scale)
        {
            var d = point - center;
            var newPoint = d.ToVector2() * scale;
            return newPoint.ToPoint() + center;
        }

        private static Point RotatePoint(Point point, Point center, double angle)
        {
            var cos = System.Math.Cos(angle);
            var sin = System.Math.Sin(angle);
            var d = point - center;
            return new Point
            {
                X = (int)(cos * d.X - sin * d.Y + center.X),
                Y = (int)(sin * d.X + cos * d.Y + center.Y)
            };
        }
    }
}