using DALI.ToolKit;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace DALI.ToolKit.IO
{
    public static class InkmlExtensions
    {
        static readonly string inkmlPointFormat = "{0:0.####} {1:0.####}";
        static readonly string inkmlPointFormatPressure = "{0:0.####} {1:0.####} {2:0.####}";
        static readonly string inkmlPointFormatPressureTime = "{0:0.####} {1:0.####} {2:0.####} {3:0}";
        static readonly string inkmlSeparator = ", ";

        public static string ToInkml(this IEnumerable<DaliStrokePoint> trace, bool pressure = true)
        {
            return String.Join(inkmlSeparator, trace.Select(p => p.ToInkml(pressure)));
        }

        public static string ToInkml(this DaliStrokePoint point, bool pressure = true)
        {
            if (pressure)
            {
                return String.Format(CultureInfo.InvariantCulture, inkmlPointFormatPressureTime, point.X, point.Y, point.P, point.T.TotalMilliseconds);
            }
            else
                return String.Format(CultureInfo.InvariantCulture, inkmlPointFormat, point.X, point.Y);
        }

        public static DaliStroke ToTrace(this string inkml, DateTime? startTime = null)
        {
            return new DaliStroke(inkml.Split(',').Select(ps => InkmlExtensions.ToTracePoint(ps)));//.ToTrace(startTime);
        }

        public static DaliStrokePoint ToTracePoint(this string inkml, bool isPenUp = false)
        {
            var split = inkml.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (split.Length == 4)
                return new DaliStrokePoint(Double.Parse(split[0], CultureInfo.InvariantCulture), Double.Parse(split[1], CultureInfo.InvariantCulture), TimeSpan.FromMilliseconds(Int32.Parse(split[3])), Single.Parse(split[2], CultureInfo.InvariantCulture));
            else
                throw new InvalidOperationException("Wrong format " + inkml);
       }

    }
}
