//
// Copyright (c) 2022, MindFusion LLC - Bulgaria.
//

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Windows.Forms;

using MindFusion.Diagramming;
using MindFusion.Diagramming.WinForms;


namespace MindFusion.Diagramming.WinForms.Samples.CS.VisioStencils
{
	/// <summary>
	/// Summary description for MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();

			nodeListView.ClearNodes();
			diagramView.AllowDrop = true;

			var stencilFolder = StencilFolder;
			if (!string.IsNullOrEmpty(stencilFolder))
				LoadStencil(System.IO.Path.Combine(stencilFolder, "Countries.vsx"));
		}

		private void menuItemOpenStencil_Click(object sender, EventArgs e)
		{
			var dialog = new OpenFileDialog();
			dialog.Filter = "Visio stencils (*.vsx)|*.vsx|All Files|*.*||";
			dialog.InitialDirectory = StencilFolder;
			if (dialog.ShowDialog(this) == DialogResult.OK)
				LoadStencil(dialog.FileName);
		}

		private void LoadStencil(string fileName)
		{
			var stencil = VisioStencil.LoadFromXml(fileName);

			// Load the master shapes into the NodeListView
			nodeListView.ClearNodes();
			foreach (var master in stencil.Masters)
			{
				var node = new VisioNode(diagram);
				node.Content = VisioContent.Create(stencil, master.UniversalName);

				nodeListView.AddNode(node, master.UniversalName);
			}
		}

		private void menuItemExit_Click(object sender, EventArgs e)
		{
			Close();
		}


		public string StencilFolder
		{
			get
			{
				if (string.IsNullOrEmpty(stencilFolder))
				{
					var currentFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

					var info = new DirectoryInfo(currentFolder);
					while (info != null)
					{
						var checkFolder = System.IO.Path.Combine(
							info.FullName, @"Redistributable\VisioStencils");
						if (Directory.Exists(checkFolder))
						{
							stencilFolder = checkFolder;
							break;
						}

						info = info.Parent;
					}
				}

				return stencilFolder;
			}
		}


		private string stencilFolder;
	}
}
