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

namespace NotepadEnhanced.Helpers
{
    /// <summary>
    /// Short for string operations, this class holds helper functions pertaining to strings
    /// </summary>
    static class StringOps
    {
        /// <summary>
        /// The tab text is to be auto-elipsised. This method gets applies the overflow notation
        /// to the text if it exceeds a certain amount of characters.
        /// </summary>
        public static string GetElipsisedText(string text)
        {
            const int MAX_LENGTH = 40;

            if (text.Length > MAX_LENGTH)
            {
                string shortened = text.Substring(0, MAX_LENGTH - 3);
                return shortened + "...";
            }

            return text;
        }

        public static string MakeUrlFriendly(string link)
        {
            link = link.ToLower();

            if (!link.Contains(@"http://"))
                link = link.Insert(0, @"http://");

            return link;
        }

        public static string CapitalizeFirstLetter(string text)
        {
            string firstLetter = text[0].ToString();
            firstLetter = firstLetter.ToUpper();
            text = text.Remove(0, 1);
            return text.Insert(0, firstLetter);;
        }

        /// <summary>
        /// Determines if a cher is has one of the characters in a specified char array
        /// </summary>
        private static bool ContainsChar(char input, params char[] patterns)
        {
            for (var i = 0; i < patterns.Length; i++)
            {
                if (patterns[i].Equals(input)) return true;
            }

            return false;
        }

        private static bool IsCharFileNameSafe(char c)
        {
            char[] safeSymbols = { '-', ' ', '\b', '_', '.' };
            bool isAcceptedSymbol = ContainsChar(c, safeSymbols);
            // if character is alphanumeric and is a safe symbol return true
            return (char.IsLetterOrDigit(c) || isAcceptedSymbol);
        }

        public static string MakeStringFilenameSafe(string text)
        {
            var builder = new StringBuilder();

            foreach (char c in text.Where(IsCharFileNameSafe))
                builder.Append(c);

            return builder.ToString();
        }
    }
}
