using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WUApiLib;

namespace Valg.EVA.Skanning.Services.Security
{
	public class WindowsUpdates
	{
		public List<WindowsUpdate> InstalledUpdates { get; set; } = new List<WindowsUpdate>();
		private readonly UpdateSession _updateSession = (UpdateSession)Activator.CreateInstance(Type.GetTypeFromProgID("Microsoft.Update.Session"));

		public WindowsUpdates()
		{
			GetAllInstalledUpdates();
		}

		public bool IsKBInstalled(string KB)
		{
			return InstalledUpdates.Any(p => string.Equals(p.KnowledgeBase, KB, StringComparison.InvariantCultureIgnoreCase));
		}

		private void GetAllInstalledUpdates()
		{
			var updateSearcher = _updateSession.CreateUpdateSearcher();
			var updateHistory = updateSearcher.QueryHistory(0, updateSearcher.GetTotalHistoryCount());
			foreach (dynamic update in updateHistory)
			{
				InstalledUpdates.Add(new WindowsUpdate()
				{
					KnowledgeBase = GetKbNumber(update.Title),
					Installed = update.Date,
					Title = update.Title,
					Description = update.Description
				});
			}
		}

		private string GetKbNumber(string title)
		{
			var regexPattern = new Regex(@"(KB\d+)");
			return regexPattern.Match(title).Value;
		}
	}
}

