using MindFusion.Diagramming;
using MindFusion.Drawing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace LayeredLayout
{
 	 // 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;

			MindFusion.Drawing.LinearGradientBrush brush = new MindFusion.Drawing.LinearGradientBrush(Color.FromRgb(0, 52, 102), 
				Color.FromRgb(224, 233, 233), 90);

			diagram.ShapeNodeStyle.Brush = brush;
			diagram.ShapeNodeStyle.Stroke = new MindFusion.Drawing.SolidBrush(Color.FromRgb(0, 52, 102));
			diagram.DiagramLinkStyle.Stroke = new MindFusion.Drawing.SolidBrush(Color.FromRgb(0, 52, 102));
			diagram.DiagramLinkStyle.StrokeThickness = 1;

			random = new Random();
		}

		private void OnRandomClick(object sender, EventArgs e)
		{
			RandomGraph();
			Arrange();
		}

		private void Arrange()
		{
			MindFusion.Diagramming.Layout.LayeredLayout layout = new MindFusion.Diagramming.Layout.LayeredLayout();
			layout.Anchoring = Anchoring.Reassign;
			layout.EnforceLinkFlow = true;
			layout.StraightenLongLinks = true;
			layout.NodeDistance = 10;
			layout.LayerDistance = 15;
			layout.Arrange(diagram);

			diagram.ResizeToFitItems(5);
			diagramView.ZoomToFit();

			diagram.ZoomFactor *= 2;
			diagram.ScrollToggle.IsActive = true;
		}

		private void RandomGraph()
		{
			diagram.ClearAll();

			for (int i = 0; i < 30; ++i)
			{
				int c = diagram.Nodes.Count;
				int g = 2 + random.Next(15);
				for (int j = 0; j < g; ++j)
				{
					ShapeNode node = diagram.Factory.CreateShapeNode(0, 0, 40, 40);
					node.AnchorPattern = AnchorPattern.TopInBottomOut;
					if (j > 0)
						diagram.Factory.CreateDiagramLink(diagram.Nodes[diagram.Nodes.Count - 2], node);
				}
				if (i > 0)
				{
					for (int j = 0; j < 1 + random.Next(3); ++j)
						diagram.Factory.CreateDiagramLink(
							diagram.Nodes[random.Next(c)],
							diagram.Nodes[c + random.Next(g)]);
				}
			}
		}



		Diagram diagram;
		readonly Rectangle bounds;
		readonly Brush[] brushes;
		readonly Random random;
	}
}
