using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;

namespace LeafWeb.Core.Utility
{
	public static class StringExtensions
	{
		public static string SplitCamelCase(this string str)
		{
			return str.Aggregate(
				string.Empty,
				(current, c) =>
				current + (char.IsUpper(c) && current.Length > 0 ? " " + c : c.ToString(CultureInfo.InvariantCulture)));
		}

		public static string[] SplitNewLine(this string str)
		{
			return str.Split(new[] {"\n", "\r\n"}, StringSplitOptions.None);
		}

		public static string LowercaseFirst(string s)
		{
			// Check for empty string.
			if (string.IsNullOrEmpty(s))
			{
				return string.Empty;
			}
			// Return char and concat substring.
			return char.ToLowerInvariant(s[0]) + s.Substring(1);
		}

		public static string WhitespaceToUnderscore(this string str)
		{
			return Regex.Replace(str, @"\s+", "_");
		}

		public static byte[] GetBytes(this string str)
		{
			return System.Text.Encoding.Default.GetBytes(str);
		}

		public static string GetString(this byte[] bytes)
		{
			return System.Text.Encoding.Default.GetString(bytes);
		}

		public static string FilterAlphaNumeric(this string input)
		{
			return Regex.Replace(input, @"[^\w_]", "");
		}

		public static string FilterValidFilename(this string input)
		{
			return Regex.Replace(input, @"[^\w_\-\.]", "");
		}

		public static string FilenameFromPath(this string path)
		{
			return Regex.Replace(path, @".*/([^/]*$)", "$1");
		}

		public static string TrimEndNewLine(this string input)
		{
			return input.TrimEnd('\r', '\n');
		}

		public static string Join<T>(this IEnumerable<T> enumerable, string separator)
		{
			return string.Join(separator, enumerable);
		}
	}
}
