using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using DesertPaintCodex.Models;
using DesertPaintCodex.Util;
namespace DesertPaintCodex.Services
{
internal static class PaletteService
{
private static readonly Regex ColorEntry = new(@"\#(?<red>\w\w)(?<green>\w\w)(?<blue>\w\w)\s*(?<name>\w+)");
public static List<PaintColor> Colors { get; } = new();
private static bool _initialized = false;
public static void Initialize()
{
if (_initialized) return;
string? colorsPath = FileUtils.FindApplicationResourceFile("colors.txt");
Debug.Assert(colorsPath != null);
Load(colorsPath);
_initialized = true;
}
public static void Load(string file)
{
using StreamReader reader = new StreamReader(file);
string? line;
while ((line = reader.ReadLine()) != null)
{
Match match = ColorEntry.Match(line);
if (match.Success)
{
Colors.Add(new PaintColor(match.Groups["name"].Value,
match.Groups["red"].Value,
match.Groups["green"].Value,
match.Groups["blue"].Value));
}
}
}
public static int Count => Colors.Count;
public static string FindNearest(PaintColor color)
{
int bestDistSq = int.MaxValue;
PaintColor? bestColor = null;
foreach (PaintColor paintColor in Colors)
{
int distSq = paintColor.GetDistanceSquared(color);
if (distSq >= bestDistSq) continue;
bestDistSq = distSq;
bestColor = paintColor;
}
Debug.Assert(bestColor != null);
return bestColor.Name;
}
}
}