using System.Diagnostics.CodeAnalysis;
using System.Text;
using JetBrains.Annotations;

namespace AyCode.Utils.Extensions
{
    public static class StringExtensions
    {
        //[ContractAnnotation("str:null => true; str:notnull <= false")]
        //[return: NotNullIfNotNull(nameof(str))]
        public static bool IsNullOrEmpty([NotNullWhen(false)] this string? str) => str == null || str.Length == 0;

        //[ContractAnnotation("str:null => true;; str:notnull <= false")]
        //[return: NotNullIfNotNull(nameof(str))]
        public static bool IsNullOrWhiteSpace([NotNullWhen(false)] this string? str)
        {
            if (str == null || str.Length == 0) return true;
            if (!char.IsWhiteSpace(str[0])) return false;

            for (var i = 1; i < str.Length; i++)
            {
                if (!char.IsWhiteSpace(str[i]))
                    return false;
            }

            return true;
        }

        public static string FirstLetterToUpper(string str)
        {
            if (str.IsNullOrWhiteSpace())
                return str;

            if (str.Length == 1)
                return str.ToUpper();

            str = str.ToLower();

            return char.ToUpper(str[0]) + str[1..];
        }

        
        //public static string MixCharacters(this string str1, string str2)
        //    => MixCharacters(str1?.ToCharArray(), str2?.ToCharArray());

        //public static string MixCharacters(this char[] chars1, string str2)
        //    => MixCharacters(chars1, str2?.ToCharArray());

        //public static string MixCharacters(this string str1, char[] chars2)
        //    => MixCharacters(str1?.ToCharArray(), chars2);

        /// <summary>
        /// Example : chars1=ABC, chars2=DEF ==> ADBECF 
        /// </summary>
        /// <param name="firstChars"></param>
        /// <param name="secondChars"></param>
        /// <returns></returns>
        public static string MixCharacters(this IEnumerable<char> firstChars, IEnumerable<char> secondChars)
        {
            var chars1 = firstChars as char[] ?? firstChars.ToArray();
            var chars2 = secondChars as char[] ?? secondChars.ToArray();

            if (chars1 is not { Length: > 0 }) return chars2.ToString() ?? string.Empty;
            if (chars2 is not { Length: > 0 }) return chars1.ToString() ?? string.Empty;

            var length = chars1.Length < chars2.Length ? chars1.Length : chars2.Length;
            var builder = new StringBuilder(length * 2);

            for (var i = 0; i < length; i++)
            {
                builder.Append(chars1[i]);
                builder.Append(chars2[i]);
            }

            return builder.ToString();
        }
    }
}
