using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;


namespace skyscraper5.src.Skyscraper.IO.PortableExecutables
{
	public static class RsrcUtility
	{
		public static VsVersionInfo TryGetVersionInfo(ImageResourceDirectory ird)
		{
			if (ird.Depth != 0)
				throw new ArgumentException(string.Format("Need the top {0}", nameof(ImageResourceDirectory), nameof(ird)));

			ImageResourceDirectoryEntry manifestDirectoryEntry = ird.Entries.FirstOrDefault(x => x.UsingNameId && x.NameId == 16);
			if (manifestDirectoryEntry == null)
				throw new ResourceEntryException("Could not find manifest resource");

			ImageResourceDirectory nameDirectory = (ImageResourceDirectory)manifestDirectoryEntry.Payload;
			ImageResourceDirectoryEntry nameDirectoryEntry = nameDirectory.Entries.FirstOrDefault();
			if (nameDirectoryEntry == null)
				throw new ResourceEntryException("Could not find the first entry in the manifest resource.");

			ImageResourceDirectory languageDirectory = (ImageResourceDirectory)nameDirectoryEntry.Payload;
			ImageResourceDirectoryEntry languageDirectoryEntry = languageDirectory.Entries.FirstOrDefault();
			if (languageDirectory == null)
				throw new ResourceEntryException("Could not find the first entry in the manifest langauge resource.");

			ImageResourceDataEntry languageData =  (ImageResourceDataEntry)languageDirectoryEntry.Payload;
			byte[] languageDataBuffer = languageData.Buffer;

			return new VsVersionInfo(languageDataBuffer);
		}
	}
}
