using System.Globalization;
using System.Text;
namespace Febe.Core.Library;
///
/// Normalization for the search of the library (spec §4.6: account name and caption): lowercase, without accents,
/// with runs of white space collapsed. «Perché» and «perche» match.
///
public static class TextSearch
{
public static string Normalize(string? text)
{
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
var decomposed = text.Normalize(NormalizationForm.FormD);
var builder = new StringBuilder(decomposed.Length);
var lastWasSpace = false;
foreach (var ch in decomposed)
{
var category = CharUnicodeInfo.GetUnicodeCategory(ch);
if (category is UnicodeCategory.NonSpacingMark or UnicodeCategory.SpacingCombiningMark or UnicodeCategory.EnclosingMark)
{
continue;
}
if (char.IsWhiteSpace(ch))
{
if (!lastWasSpace && builder.Length > 0)
{
builder.Append(' ');
}
lastWasSpace = true;
continue;
}
lastWasSpace = false;
builder.Append(char.ToLowerInvariant(ch));
}
return builder.ToString().TrimEnd().Normalize(NormalizationForm.FormC);
}
/// Text indexed for an entry: caption and author.
public static string ForEntry(string? caption, string? author) =>
Normalize(string.Join(' ', new[] { caption, author }.Where(s => !string.IsNullOrWhiteSpace(s))));
/// A LIKE pattern «%term%» with %, _ and \ escaped (use with ESCAPE '\').
public static string LikePattern(string normalizedTerm)
{
ArgumentNullException.ThrowIfNull(normalizedTerm);
var escaped = normalizedTerm.Replace("\\", "\\\\", StringComparison.Ordinal)
.Replace("%", "\\%", StringComparison.Ordinal)
.Replace("_", "\\_", StringComparison.Ordinal);
return "%" + escaped + "%";
}
}