using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Analyze
	{
	// load the XML info
	class Loader
		{

		public class XMLArgs : EventArgs
			{
			public enum Type
				{
				File,
				Suffix,
				TotalStat, 
				Error
				};
			public Type type;
			public string Message;
			public InstructionStat instructionStat;
			public FileStat fileStat;
			}
		public event EventHandler<XMLArgs> MessageEvent;

		protected void OnMessage(string message, XMLArgs.Type type, InstructionStat stat = null, FileStat fileStat = null)
			{
			var e = MessageEvent;
			if (e != null)
				e(this, new XMLArgs() { Message = message, type = type, instructionStat = stat, fileStat = fileStat });
			}

		XElement root;
		/// <summary>
		/// Parse the given XML file
		/// </summary>
		/// <param name="XMLFileName"></param>
		public void Parse(string XMLFileName)
			{
			try
				{
				root = XElement.Load(XMLFileName);
				var files = root.Element("files");
				foreach (var file in files.Elements())
					{
					FileStat fs = new FileStat(file);
					var filename = file.Attribute("Filename").Value;
					OnMessage(filename, XMLArgs.Type.File, null, fs);
					}
				var suffixes = root.Element("suffixes");
				foreach (var suffix in suffixes.Elements())
					OnMessage(suffix.Value, XMLArgs.Type.Suffix);
				var totals = root.Element("Totals");
				var totalInst = totals.Element("instructionStats");
				foreach (var stat in totalInst.Elements())
					{
					var mn = stat.Attribute("Mnemonic").Value;
					OnMessage(mn, XMLArgs.Type.TotalStat, new InstructionStat(stat));
					}
				}
			catch (Exception e)
				{
				OnMessage("Exception: " + e.Message, XMLArgs.Type.Error);
				}
			}

		}
	}
