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 Tutorial2
{
	// 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 = diagramView.Diagram;

			bounds = new Rectangle(0, 0, 24, 6);
			var root = diagram.Factory.CreateShapeNode(bounds);
			root.Text = "Project";

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

			// Load the graph xml
			XDocument document = XDocument.Parse(text);
			CreateChildren(root, document.Root);

			var layout = new TreeLayout();
			layout.Type = TreeLayoutType.Cascading;
			layout.Direction = TreeLayoutDirections.LeftToRight;
			layout.LinkStyle = TreeLayoutLinkType.Cascading2;
			layout.NodeDistance = 3;
			layout.LevelDistance = -8;
			layout.Arrange(diagram);
		}

		void CreateChildren(DiagramNode parentDiagNode, XElement parentXmlNode)
		{
			var activities = parentXmlNode.Elements();
			foreach (var ac in activities)
			{
				if (ac.Name == "Activity")
				{
					var node = diagram.Factory.CreateShapeNode(bounds);
					node.Text = ac.Attribute(XName.Get("Name")).Value;
					diagram.Factory.CreateDiagramLink(parentDiagNode, node);
					CreateChildren(node, ac);
				}
			}
		}

		Rectangle bounds;
		Diagram diagram;
	}
}
