using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace skyscraper8.Ietf.FLUTE
{
	internal class FluteUtilities
	{
		private static XmlSerializer fdtSerializer;

		public static FDTInstanceType UnpackFluteFdt(byte[] buffer)
		{
			MemoryStream ms = new MemoryStream(buffer, false);
			FDTInstanceType result = UnpackFluteFdt(ms);
			ms.Close();
			ms.Dispose();
			return result;
		}

		public static FDTInstanceType UnpackFluteFdt(Stream ms)
		{
			if (fdtSerializer == null)
				fdtSerializer = new XmlSerializer(typeof(FDTInstanceType));

			try
			{

				FDTInstanceType result = (FDTInstanceType)fdtSerializer.Deserialize(ms);
				return result;
			}
			catch (InvalidOperationException e)
			{
				Console.WriteLine(e);
				return null;
			}
		}

		public static bool IsXmlWellFormed(Stream xmlStream)
		{
			try
			{
				var settings = new XmlReaderSettings
				{
					ConformanceLevel = ConformanceLevel.Document,
					DtdProcessing = DtdProcessing.Ignore,
					IgnoreComments = true,
					IgnoreWhitespace = true
				};

				XmlReader xmlReader = XmlReader.Create(xmlStream, settings);

				while (xmlReader.Read()) { } // Just read through the document
				return true;
			}
			catch (XmlException)
			{
				return false;
			}
		}

	}
}
