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

namespace LLNet.GUI
{
    public class Hash
    {
        #region "funciones publicas"
        /// <summary>Obtiene el valor de dispersion
        /// </summary>
        /// <param name="user">Usuario asignado por Puntos Naranja</param>
        /// <param name="pwd">Clave asignada por Puntos Naranja</param>
        /// <returns></returns>
        public static string get(string user, string pwd)
        {
            try
            {
                SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                string hshRnd = hex2String(sha.ComputeHash(encoding.GetBytes(Convert.ToString(getRnd(1, 100))))).ToUpper();
                return hex2String(sha.ComputeHash(encoding.GetBytes(hshRnd + hex2String(sha.ComputeHash(encoding.GetBytes(user + pwd))).ToUpper()))) + hshRnd;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        #endregion

        #region "funciones privadas"
        /// <summary> Convierte un arreglo de bytes a un string
        /// </summary>
        /// <param name="bytes">Arreglo de bytes</param>
        /// <returns></returns>
        private static string hex2String(byte[] bytes)
        {
            string hexString = "";
            try
            {
                for (int i = 0; i <= bytes.Length - 1; i++)
                {
                    hexString += bytes[i].ToString("X2");
                }
                return hexString;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary> Obtiene un valor aleatorio entre dos valores definidos
        /// </summary>
        /// <param name="MaxNumber">Valor minimo</param>
        /// <param name="MinNumber">Valor maximo</param>
        /// <returns></returns>
        private static int getRnd(int MaxNumber, int MinNumber)
        {
            try
            {
                MinNumber = 0;
                Random r = new Random(System.DateTime.Now.Millisecond);
                if (MinNumber > MaxNumber)
                {
                    int t = MinNumber;
                    MinNumber = MaxNumber;
                    MaxNumber = t;
                }
                return r.Next(MinNumber, MaxNumber);
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
        #endregion
    }
}
