using System.Reflection;
using System.ServiceModel.Syndication;
using System.Text;
using System.Xml;

namespace zotanpw.Backend;

public static class Utils {
	public static readonly string Version =
		((AssemblyInformationalVersionAttribute)Assembly.GetEntryAssembly()!.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)[0])
		.InformationalVersion[6..];

	public static readonly string LinkVersion = Version[..8];

	// Works up to 79, doubt i'll have >=80 minute read time blog posts
	public static string a_an(int number) {
		if (number >= 80)
			throw new ArgumentOutOfRangeException(nameof(number));

		return number switch {
			8  => "an",
			11 => "an",
			18 => "an",
			_  => "a"
		};
	}

	public static string ToXmlString(this SyndicationFeedFormatter feed) {
		using var sw = new StringWriterWithEncoding(Encoding.UTF8);
		using (var xw = XmlWriter.Create(sw, new XmlWriterSettings { Encoding = Encoding.UTF8 }))
			feed.WriteTo(xw);

		return sw.ToString();
	}

	private sealed class StringWriterWithEncoding : StringWriter {
		public StringWriterWithEncoding(Encoding encoding) => Encoding = encoding;

		public override Encoding Encoding { get; }
	}
}
