using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Xml;
using Machinations.FromFlash.graph;
using Machinations.FromFlash.machinations.model;

namespace Machinations
{
    public class SimlinkModel
    {
        private readonly MachinationsNode m_node;
        private Point m_position;
        private readonly HashSet<MachinationsConnection> m_connections;
        private readonly List<int> m_connectionIds; 

        public SimlinkModel(MachinationsNode node, Point position) : this(node)
        {
            m_position = position;
        }

        public SimlinkModel(MachinationsNode node, XmlElement element):this(node)
        {
            double x = double.Parse(element.GetAttribute("x"), CultureInfo.InvariantCulture);
            double y = double.Parse(element.GetAttribute("y"), CultureInfo.InvariantCulture);
            m_position = new Point(x, y);
            foreach (XmlElement connectionElement in element.ChildNodes)
            {
                m_connectionIds.Add(int.Parse(connectionElement.GetAttribute("id")));
            }
        }

        private SimlinkModel(MachinationsNode node)
        {
            m_node = node;
            node.AddSimlink(this);
            m_connectionIds = new List<int>();
            m_connections = new HashSet<MachinationsConnection>();
        }

        public MachinationsNode Node
        {
            get { return m_node; }
        }

        public Point Position
        {
            get { return m_position; }
            set { m_position = value; }
        }

        public HashSet<MachinationsConnection> Connections
        {
            get { return m_connections; }
        }


        public void Dispose()
        {
            m_node.RemoveSimlink(this);
        }

        public void FinishLoading(List<GraphElement> elements)
        {
            m_connectionIds.ForEach(id => m_connections.Add((MachinationsConnection)elements[id]));
        }

        public void GenerateXml(XmlDocument document, XmlElement parentElement)
        {
            XmlElement simlinkElement = (XmlElement)parentElement.AppendChild(document.CreateElement("simlink"));
            simlinkElement.SetAttribute("x", Math.Round(Position.X) + "");
            simlinkElement.SetAttribute("y", Math.Round(Position.Y) + "");
            foreach (var connection in Connections)
            {
                var element = document.CreateElement("connection");
                element.SetAttribute("id", connection.Id.ToString());
                simlinkElement.AppendChild(element);
            }
        }
    }
}
