using Grasshopper.Kernel.Types.Transforms;
using Rhino;
using Rhino.Geometry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EmreIstikam001.component.TehranOffice.Components.ÇİZİM_YARDIMCILARI.DetailSymbol
{
    public static class GeometryCreator
    {
        /// <summary>
        /// Creates the geometry data for the detail symbol based on the user inputs.
        /// </summary>
        /// <param name="rectangle">The rectangle polyline.</param>
        /// <param name="leaderPoints">The points for the leader.</param>
        /// <param name="DetailName">The axis identifier text.</param>
        /// <param name="scale">The scale factor.</param>
        /// <returns>A GeometryData object containing the created geometry.</returns>
        public static GeometryData CreateGeometry(Polyline rectangle, List<Point3d> leaderPoints, string DetailName, double scale)
        {
            var doc = RhinoDoc.ActiveDoc;
            var geometryData = new GeometryData();

            // Process the rectangle
            if (rectangle != null)
            {
                var rectangleSegments = rectangle.ToNurbsCurve().DuplicateSegments();
                geometryData.Curves.AddRange(rectangleSegments);
            }

            // Process the leader
            if (leaderPoints != null && leaderPoints.Count >= 2)
            {
                // Determine the leader style based on scale
                string styleName = GetDimensionStyleName(scale, 2.5);
                var leaderStyle = doc.DimStyles.FindName(styleName) ?? doc.DimStyles.Current;

                // Adjust the leader points
                var adjustedLeaderPoints = AdjustLeaderPoints(leaderPoints, scale);

                // Create the leader
                var leader = Leader.CreateWithRichText("", Plane.WorldXY, leaderStyle, adjustedLeaderPoints.ToArray());

                geometryData.Leaders.Add(leader);

                // Create the text entity and filleted rectangle
                var textEntity = CreateTextEntity(leader, DetailName, scale);
                if (textEntity != null)
                {
                    geometryData.Texts.Add(textEntity.Item1);
                    geometryData.FilletRectangles.Add(textEntity.Item2);
                }
            }

            return geometryData;
        }

        /// <summary>
        /// Generates the dimension style name based on scale and text height.
        /// </summary>
        internal static string GetDimensionStyleName(double scale, double textHeight)
        {
            return scale > 9 ? $"PCY {textHeight}mm 1/{scale}" : $"PCY {textHeight}mm 1/0{scale}";
        }

        /// <summary>
        /// Adjusts the leader points based on the scale and initial direction.
        /// </summary>
        public static List<Point3d> AdjustLeaderPoints(List<Point3d> leaderPoints, double scale)
        {
            var adjustedPoints = new List<Point3d>(leaderPoints);
            var pt3 = leaderPoints[1];

            // Move the point along the X-axis based on scale
            pt3.Transform(Transform.Translation(Vector3d.XAxis * 3 * scale));

            // Detect right-to-left selection and adjust accordingly
            if (leaderPoints[0].X > leaderPoints[1].X)
                pt3.Transform(Transform.Translation(-Vector3d.XAxis * 6 * scale));

            adjustedPoints.Add(pt3);
            return adjustedPoints;
        }

        /// <summary>
        /// Creates the text entity and its surrounding filleted rectangle.
        /// </summary>
        internal static Tuple<TextEntity, Curve> CreateTextEntity(Leader leader, string text, double scale)
        {
            var doc = RhinoDoc.ActiveDoc;
            var Pt = leader.Points3D[2];
            double baseTextHeight = 2.5;
            if (Pt == Point3d.Unset)
                return null;

            var xAxis = doc.Views.ActiveView.ActiveViewport.ConstructionPlane().XAxis;
            var yAxis = doc.Views.ActiveView.ActiveViewport.ConstructionPlane().YAxis;

            var txtObj = new TextEntity
            {
                Text = text,
                Plane = new Plane(Pt, xAxis, yAxis),
                TextHeight = baseTextHeight,
                Justification = TextJustification.MiddleCenter
            };
            Plane recplane;
            // Determine the text style based on scale
            string styleName = GetDimensionStyleName(scale, baseTextHeight);
            var textStyle = doc.DimStyles.FindName(styleName) ?? doc.DimStyles.Current;
            txtObj.ParentDimensionStyle = textStyle;

            // Calculate text dimensions
            var txtBbox = txtObj.GetBoundingBox(true);
            var xDim = txtBbox.Max.X - txtBbox.Min.X;
            var yDim = txtBbox.Max.Y - txtBbox.Min.Y;

            // Adjust the text position based on leader direction
            if (leader.Points3D[0].X > leader.Points3D[1].X)
            {
                txtObj.Plane = new Plane(Pt + new Vector3d((-1 * xDim), 0, 0), xAxis, yAxis);
            }
            else
            {
                txtObj.Plane = new Plane(Pt + new Vector3d(0, 0, 0), xAxis, yAxis);
            }

            //// Create the surrounding rectangle
            //if (leader.Points3D[0].X > leader.Points3D[1].X)
            //     recplane = new Plane(Pt + new Vector3d(-Math.Max(xDim / 2 + 6, 6) * scale, 0, 0), xAxis, yAxis);
            //else
                //recplane = new Plane(Pt + new Vector3d(Math.Max(xDim / 2 + 6, 6) * scale, 0, 0), xAxis, yAxis);

            var rectWidth = Math.Max(xDim + 5, 0) * scale;
            var rectHeight = Math.Max(yDim , 0) * scale;
            var rectangle = new Rectangle3d(txtObj.Plane, rectWidth, rectHeight);
            // Create filleted corners
            var filletRadius = rectHeight / 2;
            List<Curve> recsegments = new List<Curve>();
            recsegments.AddRange(rectangle.ToNurbsCurve().DuplicateSegments());
            var translation = new Vector3d(Point3d.Origin);
            var translation2 = new Vector3d(Point3d.Origin);
            if (leader.Points3D[0].X > leader.Points3D[1].X)
            {
                Point3d recMid1 = recsegments[1].PointAtLength(recsegments[1].GetLength() / 2);
                Vector3d transformRec = leader.Points3D[2] - recMid1;
                Vector3d transformText = new Vector3d(-1 * (rectWidth / 2 - 2), (1 * (rectHeight / 2) - 0.5), 0);
                translation = transformRec;
                translation2 = transformText;
            }
            else
            {
                Point3d recMid2 = recsegments[3].PointAtLength(recsegments[3].GetLength() / 2);
                Vector3d transformRec2 = leader.Points3D[2] -recMid2;
                Vector3d transformText = new Vector3d((rectWidth/2 -2), (1 * (rectHeight / 2)-0.5), 0);
                translation = transformRec2;
                translation2 = transformText;
            }

           
            
            var filletedCurve = Curve.CreateFilletCornersCurve(rectangle.ToNurbsCurve(), filletRadius, 0.01, 0.01);
             //Transform the rectangle to center it around the text
            //var translation = new Vector3d(-1 * (rectHeight/2) * scale * yAxis);
            rectangle.Transform(Transform.Translation(translation));
            txtObj.Transform(Transform.Translation(translation2));



            return new Tuple<TextEntity, Curve>(txtObj, rectangle.ToNurbsCurve());
        }
    }
}

there is a problem in the creating and trasfering the text object and rectangle that when the scale is set to anything higher that 1 the position of objects get wrong toward each other and intersect each other while the text  should always be in the center of rectangle and  middle of the rectangle  segment should be at the 3rd point of leader