using System;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
using Strata.Configuration.Client.Models.Jazz;

namespace Strata.Base.Internal.Encryptors
{

    public class UserGUIDEncryptionMethod : IPasswordEncryptionMethod
    {

        #region  Declarations 

        private const int NUMBER_ITERATIONS = 100000;

        #endregion

        #region  Methods 

        public string Encode(string username, string anOrgPin, string aNewPassword, Guid aUserGUID, string aSalt)
        {
            string salt = aUserGUID.ToString() + ConfigurationManager.AppSettings[nameof(StrataJazzOptions.UserGuidEncryptionKey)];

            string result = GetHashedValue(aNewPassword, salt);
            for (int i = 1; i <= NUMBER_ITERATIONS; i++)
                result = GetHashedValue(result);

            return result;
        }

        private static string GetHashedValue(string aValue)
        {

            // Create an instance of the sha encrypter
            using (HashAlgorithm hasher = SHA256.Create())
            {
                return Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(aValue)));
            }

        }

        private static string GetHashedValue(string aValue, string aSalt)
        {
            return GetHashedValue(aValue + aSalt);
        }

        #endregion

    }

}