using SvgPathProperties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace PCUT.Extensions.Converters
{
    internal class PolygonElementConverter : PathConverter
    {
        private static readonly string[] PolygonExcludedAttributes = new[] { "transform", "points" };
        protected override IEnumerable<string> ExcludedAttributes => PolygonExcludedAttributes;

        internal PolygonElementConverter()
        {
        }

        protected override bool CanApply(XElement element) => element.Name.LocalName == "polygon";

        protected override SvgPath GetPathFromElement(XElement element)
        {
            var points = GetPolygonPoints(element.Attribute("points")?.Value);
            if (!points.Any())
                return null;

            var builder = new StringBuilder();
            foreach (var (x, y) in points)
            {
                builder.Append(builder.Length == 0 ? "M " : "L ").Append($"{x} {y}");
            }
            builder.Append("Z");
            return new SvgPath(builder.ToString(), unarc: true);
        }

        private IEnumerable<(double X, double Y)> GetPolygonPoints(string pointsValue)
        {
            if (pointsValue == null)
                yield break;

            var points = pointsValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (points.Length % 2 != 0)
                yield break;

            for (int i = 0; i < points.Length; i += 2)
            {
                yield return (double.Parse(points[i]), double.Parse(points[i + 1]));
            }
            yield break;
        }
    }
}
