using System.Text;

namespace Ladaer.BackEnd.Infrastructures.Libs
{
    public static class RandomFunc
    {
        public static string RandomCode(int size)
        {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var random = new Random();
            return new string(
                Enumerable.Repeat(chars, size)
                    .Select(s => s[random.Next(s.Length)])
                    .ToArray());
        }
        public static int RandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }
        public static string InitializationCode(long begin, string firstSegment = "1009")
        {
            begin = begin + 1;
            string deFirstSegment = "1009";
            if (!string.IsNullOrWhiteSpace(firstSegment))
                deFirstSegment = firstSegment;
            var degit = GenerateLuhn(begin.ToString());
            if (string.IsNullOrEmpty(degit) || string.IsNullOrWhiteSpace(degit)) degit = "0";
            if (degit.Length > 1) degit = degit.Substring(0, 1);
            var after = "0000000000";
            after = after.Substring(0, 10 - begin.ToString().Length) + begin;
            string result = $"{deFirstSegment}{after.Substring(0, 3)}{degit}{after.Substring(4)}";
            return result;
        }
        public static string GenerateLuhn(string num)
        {
            int[] array = StringToReversedIntArray(num);
            int sum = 0;
            for (int i = 0; i < array.Length; i++)
            {
                if (i % 2 == 0)
                {
                    sum += array[i] >= 10 ? array[i] * 2 - 9 : array[i];
                }
                else
                {
                    sum += array[i];
                }
            }
            return (10 - sum % 10) % 10 + "";
        }
        public static int[] StringToReversedIntArray(string num)
        {
            byte[] bs = Encoding.ASCII.GetBytes(num);
            int[] t = new int[bs.Length];
            for (int i = 0; i < bs.Length; i++)
            {
                t[i] = bs[bs.Length - 1 - i] - 48;
            }
            return t;
        }
        public static bool ValidateLuhn(string num)
        {
            int[] array = StringToReversedIntArray(num);
            int sum = 0;
            for (int i = 0; i < array.Length; i++)
            {
                if (i % 2 != 0)
                {
                    sum += array[i] >= 10 ? array[i] * 2 - 9 : array[i];
                }
                else
                {
                    sum += array[i];
                }
            }
            if (sum % 10 == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
