using System.Globalization;
using Nalu.Web.PostProcessors;

namespace Nalu.Web.PostProcessors;

public class CapitalizeProperName : IPostProcessor
{
    public string Name => "capitalize_proper_name";

    private static readonly HashSet<string> LowercaseWords = new(StringComparer.OrdinalIgnoreCase)
    {
        "de", "da", "do", "das", "dos", "e", "em", "na", "no", "nas", "nos", "van", "von", "del"
    };

    public ProcessorResult Process(string? value)
    {
        if (string.IsNullOrWhiteSpace(value)) return ProcessorResult.Ok(value);

        var words = value.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        var result = new List<string>(words.Length);

        for (int i = 0; i < words.Length; i++)
        {
            var word = words[i];
            if (i > 0 && LowercaseWords.Contains(word))
                result.Add(word.ToLowerInvariant());
            else
                result.Add(CultureInfo.InvariantCulture.TextInfo.ToTitleCase(word.ToLowerInvariant()));
        }

        return ProcessorResult.Ok(string.Join(' ', result));
    }
}
