using MindFusion.Diagramming;
using MindFusion.Diagramming.Layout;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Xamarin.Forms;

namespace Tutorial1
{
	// Learn more about making custom code visible in the Xamarin.Forms previewer
	// by visiting https://aka.ms/xamarinforms-previewer
	[DesignTimeVisible(false)]
	public partial class MainPage : ContentPage
	{
		public MainPage()
		{
			InitializeComponent();

			Diagram diagram = diagramView.Diagram;

			var nodeMap = new Dictionary<string, DiagramNode>();
			var bounds = new Rectangle(0, 0, 18, 6);

			var assembly = typeof(App).GetTypeInfo().Assembly;
			Stream stream = assembly.GetManifestResourceStream("Tutorial1.SampleGraph.xml");
			string text;
			using (var reader = new StreamReader(stream))
			{
				text = reader.ReadToEnd();
			}

			// Load the graph xml
			XDocument document = XDocument.Parse(text);//"SampleGraph.xml");

			var nodes = document.Descendants("Node");
			foreach (var node in nodes)
			{
				var diagramNode = diagram.Factory.CreateShapeNode(bounds);
				nodeMap[node.Attribute("id").Value] = diagramNode;
				diagramNode.Text = node.Attribute("name").Value;
			}

			var links = document.Descendants("Link");
			foreach (var link in links)
			{
				diagram.Factory.CreateDiagramLink(
					nodeMap[link.Attribute("origin").Value],
					nodeMap[link.Attribute("target").Value]);
			}

			var layout = new LayeredLayout();
			layout.LayerDistance = 12;
			layout.Arrange(diagram);
		}
	}
}
