using Microsoft.Maui.Graphics;

using MindFusion.Diagramming;
using MindFusion.Diagramming.Components;
using MindFusion.Drawing;

using Brush = MindFusion.Drawing.Brush;
using IImage = Microsoft.Maui.Graphics.IImage;


namespace Tutorial3
{
	public class OrgChartNode : CompositeNode
	{
		static string xmlTemplate = LoadTemplate("Tutorial3.OrgChartNode.xml");

		static string LoadTemplate(string resourcePath)
		{
			var assembly = typeof(OrgChartNode).Assembly;
			using (var stream = assembly.GetManifestResourceStream(resourcePath))
			{
				if (stream == null)
				{
					throw new InvalidOperationException(
						"Could not find embedded resource.");
				}
				using (var reader = new StreamReader(stream))
					return reader.ReadToEnd();
			}
		}

		public OrgChartNode(Diagram diagram) : base(diagram)
		{
			// load components from XML template
			var rootComponent = XmlLoader.Load(xmlTemplate, this, null);
			if (rootComponent != null)
				this.Components.Add(rootComponent);

			// find components by name
			shape = (ShapeComponent)FindComponent("Shape");
			imageComponent = (ImageComponent)FindComponent("Image");
			title = (TextComponent)FindComponent("Title");
			fullName = (TextComponent)FindComponent("FullName");
			textComponent = (TextComponent)FindComponent("Text");

			// customize appearance
			title?.TextAlignment = StringAlignment.Near;
			fullName?.TextAlignment = StringAlignment.Near;
			textComponent?.TextAlignment = StringAlignment.Near;
			shape?.IsOutline = true;

			Fill = new SolidBrush(Colors.White);
			Stroke = new Pen(Colors.Black, 0.5f);
		}

		public Pen Stroke
		{
			get { return shape?.Pen; }
			set
			{
				shape?.Pen = value;
				this.Repaint();
			}
		}

		public Brush Fill
		{
			get { return shape?.Brush; }
			set { shape?.Brush = value; }
		}

		public IImage Image
		{
			get { return imageComponent?.Image; }
			set { imageComponent?.Image = value; }
		}

		public string Title
		{
			get { return title?.Text; }
			set { title?.Text = value; }
		}

		public string FullName
		{
			get { return fullName?.Text; }
			set { fullName?.Text = value; }
		}

		public string Text
		{
			get { return textComponent?.Text; }
			set { textComponent?.Text = value; }
		}

		ShapeComponent shape;
		ImageComponent imageComponent;
		TextComponent title;
		TextComponent fullName;
		TextComponent textComponent;
	}
}
