using TraceCad.Core.Model;

namespace TraceCad.Core.Geometry;

public static class GeometryTransform
{
    public static Point2 Rotate(Point2 point, Point2 pivot, double angleDeg)
    {
        var radians = angleDeg * Math.PI / 180.0;
        var cos = Math.Cos(radians);
        var sin = Math.Sin(radians);
        var dx = point.X - pivot.X;
        var dy = point.Y - pivot.Y;
        return new Point2(
            pivot.X + (dx * cos) - (dy * sin),
            pivot.Y + (dx * sin) + (dy * cos));
    }

    public static Entity Rotate(Entity entity, Point2 pivot, double angleDeg)
    {
        return entity switch
        {
            LineEntity line => line with
            {
                Start = Rotate(line.Start, pivot, angleDeg),
                End = Rotate(line.End, pivot, angleDeg)
            },
            CircleEntity circle => circle with
            {
                Center = Rotate(circle.Center, pivot, angleDeg)
            },
            ArcEntity arc => arc with
            {
                Center = Rotate(arc.Center, pivot, angleDeg),
                StartAngleDeg = GeometryHelpers.NormalizeAngleDeg(arc.StartAngleDeg + angleDeg),
                EndAngleDeg = GeometryHelpers.NormalizeAngleDeg(arc.EndAngleDeg + angleDeg)
            },
            _ => entity
        };
    }

    public static ReferenceImage Rotate(ReferenceImage reference, Point2 pivot, double angleDeg)
    {
        var origin = Rotate(
            new Point2(reference.Transform.OriginX, reference.Transform.OriginY),
            pivot,
            angleDeg);
        return reference with
        {
            Transform = reference.Transform with
            {
                OriginX = origin.X,
                OriginY = origin.Y,
                RotationDeg = GeometryHelpers.NormalizeAngleDeg(reference.Transform.RotationDeg + angleDeg)
            }
        };
    }
}
