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; }
	}

	public static string Truncate(this string input, int maxLen, string truncateMarker = "...") {
		var markerLength = truncateMarker.Length;
		if (maxLen < 1 + markerLength)
			maxLen = 1 + markerLength;
		return input.Length <= maxLen ? input : input[..(maxLen - markerLength)] + truncateMarker;
	}

	public static string GetUntil(this string input, string stopAt) {
		if (!string.IsNullOrWhiteSpace(input)) {
			if (!input.Contains(stopAt))
				return input;

			var charLocation = input.IndexOf(stopAt, StringComparison.Ordinal);
			return input[..++charLocation];
		}

		return string.Empty;
	}
}
