using System.Runtime.ExceptionServices;

namespace skyscraper5.Skyscraper
{
	public static class StringExtensions
	{
		public static bool IsNaturalNumeric(this string str)
		{
			char[] charArray = str.ToCharArray();
			foreach (char c in charArray)
			{
				if (!char.IsDigit(c))
					return false;
			}

			return true;
		}

		public static string SanitizeFileName(this string str)
		{
			char[] invalidPathChars = Path.GetInvalidPathChars();
			char[] invalidFileNameChars = Path.GetInvalidFileNameChars();

			char[] charArray = str.ToCharArray();
			for (int i = 0; i < charArray.Length; i++)
			{
				if (invalidPathChars.Contains(charArray[i]))
				{
					charArray[i] = '_';
				}

				if (invalidFileNameChars.Contains(charArray[i]))
				{
					charArray[i] = '_';
				}
			}

			return new string(charArray);
		}

		public static byte[] HexToBytes(this string hex)
		{
			return Enumerable.Range(0, hex.Length)
				.Where(x => x % 2 == 0)
				.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
				.ToArray();
		}

		public static uint HexToUint32BE(this string hex)
		{
			byte[] hexToBytes = hex.HexToBytes();
			if (hexToBytes.Length < 4)
			{
				byte[] better = new byte[4];
				Array.Copy(hexToBytes, 0, better, 0, hexToBytes.Length);
				hexToBytes = better;
			}

			(hexToBytes[3], hexToBytes[2], hexToBytes[1], hexToBytes[0]) = (hexToBytes[0], hexToBytes[1], hexToBytes[2], hexToBytes[3]);
			return BitConverter.ToUInt32(hexToBytes, 0);
		}

		public static uint HexToUint32LE(this string hex)
		{
			byte[] hexToBytes = hex.HexToBytes();
			if (hexToBytes.Length < 4)
			{
				byte[] better = new byte[4];
				Array.Copy(hexToBytes, 0, better, 0, hexToBytes.Length);
				hexToBytes = better;
			}
			
			return BitConverter.ToUInt32(hexToBytes, 0);
		}

		public static ushort HexToUInt16LE(this string hex)
		{
			byte[] hexToBytes = hex.HexToBytes();
			if (hexToBytes.Length < 2)
			{
				byte[] better = new byte[2];
				Array.Copy(hexToBytes, 0, better, 0, hexToBytes.Length);
				hexToBytes = better;
			}
			
			return BitConverter.ToUInt16(hexToBytes, 0);
		}

		public static ushort HexToUInt16BE(this string hex)
		{
			byte[] hexToBytes = hex.HexToBytes();
			if (hexToBytes.Length < 2)
			{
				byte[] better = new byte[2];
				Array.Copy(hexToBytes, 0, better, 0, hexToBytes.Length);
				hexToBytes = better;
			}

			(hexToBytes[1], hexToBytes[0]) = (hexToBytes[0], hexToBytes[1]);
			return BitConverter.ToUInt16(hexToBytes, 0);
		}

		public static byte HexToUInt8(this string hex)
		{
			byte[] hexToBytes = hex.HexToBytes();
			return hexToBytes[0];
		}
	}
}
