using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace GreenTree.Strohrmann.ERP.Core.Helper
{
    public class UserHelper : IUserHelper
    {
        /// <summary>
        /// Generates a MD5 hash from a string
        /// </summary>
        /// <param name="str">The string to encrypt.</param>
        /// <param name="lowerCase">Return hashed string in lower case.</param>
        public string HashString(string str, bool lowerCase)
        {
            if (String.IsNullOrEmpty(str))
                throw new ArgumentNullException("str", "An empty string cannot be encrypted.");

            // Byte array representation of that string
            var encodedStr = new UTF8Encoding().GetBytes(str);

            // Need MD5 to calculate the hash
            var hash = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedStr);

            // String representation (similar to UNIX format)
            var hashedStr = BitConverter.ToString(hash)
               .Replace("-", string.Empty)
               .ToLower();

            return lowerCase
                ? hashedStr.ToLower()
                : hashedStr;
        }
    }
}
