using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using CrossCutting;

namespace BallotTemplates
{
    [XmlType("ChangeField", Namespace = "urn:scan-omr:template")]
    public abstract class ChangeField : TextField
    {

        internal static ChangeField Create(ChangeFieldType type)
        {
            switch (type)
            {
                case ChangeFieldType.PersonVote:
                    return new PersonVoteField();
                case ChangeFieldType.Renumbering:
                    return new RenumberingField();
                case ChangeFieldType.Strikeout:
                    return new StrikeoutField();
                case ChangeFieldType.Affiliation:
                    return new AffiliationSelectorField();
                default:
                    throw new ArgumentException(nameof(type));
            }
        }
        
        
        
        [XmlAttribute("candidateNumber")]
        [Browsable(false)]
        public int CandidateNumber { get; set; }

        [XmlElement("gml:Polygon")]
        public string GmlPolygon { get; set; }

        [XmlIgnore]
        public ChangeFieldType Type { get; set; } = ChangeFieldType.None;

        [XmlIgnore]
        public override PointF[] BoundingPolygonPoints
        {
            get
            {
                var doc = new XmlDocument();
                doc.LoadXml(GmlPolygon);
                Debug.Assert(doc.DocumentElement != null, "doc.DocumentElement != null");
                var coordsString = doc.DocumentElement?.SelectSingleNode("coordinates")?.InnerXml;
                var points = from pair in coordsString?.Split(' ')
                             let parts = pair.Split(',')
                             select new PointF(float.Parse(parts.First(), CultureInfo.InvariantCulture), float.Parse(parts.Last(), CultureInfo.InvariantCulture));
                return points.ToArray();
            }
        }
    }

    public enum ChangeFieldType
    {
        None,
        Strikeout,
        Renumbering,
        PersonVote,
        Affiliation
    }
}
