using System.Diagnostics;

using Onnx;

using MindFusion.Diagramming;
using MindFusion.Diagramming.Layout;


namespace NeuralNet
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();

			overview.DiagramView = diagramView;
			overview.FitAll = true;
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			var diagram = diagramView.Diagram;

			var model = ModelProto.Parser.ParseFromFile(@"inception-v1-12-qdq.onnx");
			var graph = model.Graph;

			var nodeMap = new Dictionary<NodeProto, DiagramNode>();

			// create a TableNode for each graph node
			foreach (var networkNode in graph.Node)
			{
				var diagramNode = diagram.Factory.CreateTableNode(0, 0, 30, 30, 2, 1);
				diagramNode.Caption = networkNode.Name;
				diagramNode.CellFrameStyle = CellFrameStyle.Simple;
				diagramNode.Brush = new MindFusion.Drawing.SolidBrush(Color.LightGray);
				diagramNode.CaptionBackBrush = new MindFusion.Drawing.SolidBrush(Color.LightSkyBlue);
				diagramNode[0, 0].Text = "OpType:";
				diagramNode[1, 0].Text = networkNode.OpType;
				foreach (var attribute in networkNode.Attribute)
				{
					diagramNode.AddRow();
					int r = diagramNode.RowCount - 1;
					diagramNode[0, r].Text = attribute.Name;
					diagramNode[1, r].Text = attribute.Type.ToString();
				}
				diagramNode.ResizeToFitText(false, false);
				diagramNode.Caption = networkNode.Name;
				diagramNode.ConnectionStyle = TableConnectionStyle.Table;

				nodeMap[networkNode] = diagramNode;
			}

			// draw links when we find pairs of matching output -> input identifiers
			foreach (var networkNode1 in graph.Node)
			{
				foreach (var output in networkNode1.Output)
				{
					foreach (var networkNode2 in graph.Node)
					{
						if (networkNode1 == networkNode2)
							continue;

						foreach (var input in networkNode2.Input)
						{
							if (output == input)
							{
								var diagramNode1 = nodeMap[networkNode1];
								var diagramNode2 = nodeMap[networkNode2];
								diagram.Factory.CreateDiagramLink(diagramNode1, diagramNode2);
							}
						}
					}
				}
			}

			diagram.Arrange(new LayeredLayout { EnforceLinkFlow = true, IgnoreNodeSize = false });
			diagram.ResizeToFitItems(5);
		}
	}
}
