using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace DebriefingSoftware.Common
{
	public static class StringExtensions
	{
		public static string EncodeJsString(this string s)
		{
			var sb = new StringBuilder();
			sb.Append("\"");
			foreach (char c in s)
			{
				switch (c)
				{
					case '\"':
						sb.Append("\\\"");
						break;
					case '\\':
						sb.Append("\\\\");
						break;
					case '\b':
						sb.Append("\\b");
						break;
					case '\f':
						sb.Append("\\f");
						break;
					case '\n':
						sb.Append("\\n");
						break;
					case '\r':
						sb.Append("\\r");
						break;
					case '\t':
						sb.Append("\\t");
						break;
					default:
						int i = (int)c;
						if (i < 32 || i > 127)
						{
							sb.AppendFormat("\\u{0:X04}", i);
						}
						else
						{
							sb.Append(c);
						}
						break;
				}
			}
			sb.Append("\"");

			return sb.ToString();
		}
		public static string ToTitleCase(this String inputString)
		{
			if (string.IsNullOrEmpty(inputString))
				return inputString;

			return inputString.Substring(0, 1).ToUpper() + (inputString.Length > 1 ? inputString.Substring(1).ToLower() : "");
		}

		public static int? ToNullableInt(this string str)
		{
			return Parser.ParseNullableInt(str);
		}

		public static short? ToNullableShort(this string str)
		{
			return Parser.ParseNullableShort(str);
		}

		public static float? ToNullableFloat(this string str)
		{
			return Parser.ParseNullableFloat(str);
		}

		public static DateTime? ToNullableDateTime(this string str)
		{
			return Parser.ParseNullableDateTime(str);
		}

		public static List<T> GetTypesFromSeparatedString<T>(this string source, char separator = ',', bool ignoreCase = true) where T : struct
		{
			List<T> result = new List<T>();
			T _exportType;
			foreach (var exportType in source.Split(separator))
			{
				if (Enum.TryParse(exportType, ignoreCase, out _exportType) && !result.Contains(_exportType))
				{
					result.Add(_exportType);
				}
			}

			return result;
		}
	}
}
