namespace Sonex.Services.ImageSync;

using System.Text;

internal static class ConsoleHelpers
{
    public static void WriteInfo(string message) => WriteWithColor(message, ConsoleColor.Gray);

    public static void WriteSuccess(string message) => WriteWithColor(message, ConsoleColor.Green);

    public static void WriteWarning(string message) => WriteWithColor(message, ConsoleColor.Yellow);

    public static void WriteError(string message) => WriteWithColor(message, ConsoleColor.Red);

    public static string ReadPassword()
    {
        var sb = new StringBuilder();

        while (true)
        {
            ConsoleKeyInfo key = Console.ReadKey(intercept: true);

            if (key.Key == ConsoleKey.Enter)
                break;

            if (key.Key == ConsoleKey.Backspace)
            {
                if (sb.Length > 0)
                    sb.Length--;

                continue;
            }

            if (!char.IsControl(key.KeyChar))
                sb.Append(key.KeyChar);
        }

        return sb.ToString();
    }

    private static void WriteWithColor(string message, ConsoleColor color)
    {
        ConsoleColor previous = Console.ForegroundColor;

        try
        {
            Console.ForegroundColor = color;
            Console.WriteLine(message);
        }
        finally
        {
            Console.ForegroundColor = previous;
        }
    }
}
