using DALI.ToolKit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace DALI.ToolKit.IO
{
    /// <summary>
    /// InkmlFile use for Architecture project
    /// 
    /// To do : refactoring for more generic type (Geometry, Architecture ...)
    /// </summary>
    public class InkmlFile 
    {
        string filepath;
        Dictionary<string, DaliStroke> pool = new Dictionary<string, DaliStroke>();
        List<Input> inputs = new List<Input>();

        public InkmlFile(string filepath)
        {
            this.filepath = filepath;
            Name = Path.GetFileName(filepath);
        }

        public string Name
        { get; private set; }

        public string Filepath
        { get { return filepath; } }
        
        public IEnumerable<Input> Inputs { get { return inputs; } }

        public void Load()
        {
            var doc = new XmlDocument();
            doc.Load(filepath);

            XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
            manager.AddNamespace("i", @"http://www.w3.org/2003/InkML");

            // discard annotations
           /* foreach (XmlNode annotation in doc.SelectNodes("i:ink/i:annotation", manager))
            {
                var key = annotation.Attributes["type"].InnerText;

                annotations.Add(new Annotation(key, annotation.InnerText));
            }*/

            foreach (XmlNode stroke in doc.SelectNodes("i:ink/i:trace", manager))
            {
                var id = stroke.Attributes["id"].InnerText;

                if (stroke.Attributes["timeOffset"] != null)
                {
                    long timeOffsetParsed;
                    if (Int64.TryParse(stroke.Attributes["timeOffset"].InnerText, out timeOffsetParsed))
                    {
                        var timeOffset = Input.DateTimeFromUnixMilliSeconds(timeOffsetParsed);
                        pool.Add(id, InkmlExtensions.ToTrace(stroke.InnerText, timeOffset));
                    }
                }
                else
                {
                    pool.Add(id, InkmlExtensions.ToTrace(stroke.InnerText));
                }
            }

            foreach (XmlNode node in doc.SelectNodes("i:ink/i:traceGroup", manager))
            {
                Input input = new Input(node, manager, pool);
               
                inputs.Add(input);
            }
        }
    }
}
