using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Mind.Utils
{
    /// <summary>
    /// 生成一个字符对应的较短的 key。例如:生成短 Url。
    /// </summary>
    public class StringShortener
    {
        private static readonly string[][] Characters;
     
        private static readonly int IndexSize = 0x0000001F;

        static StringShortener()
        {
            var chars = "abcdefghijkmnpqrstuvwxyz23456789";
            Characters = new string[2][];
            Characters[0] = chars.Select(c => c.ToString()).ToArray();
            Characters[1] = chars.Select(c => c.ToString().ToUpper()).ToArray();

        }
        /// <summary>
        ///   
        /// </summary>
        /// <param name="source"></param>
        /// <returns>
        /// 返回包含4个元素的 string 数组,每个字符串的长度为6。
        /// </returns>
        public static string[] Generate(string source)
        {
            byte[] hashBytes;
            string[] keys = new string[4];
            string key;
            int index;

            using (var md5 = MD5.Create())
            {
                hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(source));
            }

            var factor = new object().GetHashCode();

            for (int i = 0; i < 4; i++)
            {
                index = 0x3FFFFFFF
                    & BitConverter.ToInt32(hashBytes.Skip(i * 4).Take(4).ToArray(), 0);

                key = string.Empty;

                for (int j = 0; j < 6; j++)
                {
                    key += Characters[factor & 1][IndexSize & index];
                    factor = factor >> 1;
                    index = index >> 5;
                }

                keys[i] = key;
            }

            return keys;
        }
    }
}
