using System.Text.Json; namespace View_by_Distance.Shared.Models.Stateless.Methods; internal abstract class Mapping { private static void UseKeyValuePairsSaveFaceEncoding(int locationDigits, Dictionary> keyValuePairs, string file, int id, int normalizedPixelPercentageValue, double deterministicHashCodeKey, string extensionLowered) { string json; string checkFile; string? directoryName; List collection = new(); List faces = keyValuePairs[id]; foreach (Models.Face face in faces) { if (face.FaceEncoding is null || face.Location?.NormalizedPixelPercentage is null) continue; if (normalizedPixelPercentageValue != face.Location.NormalizedPixelPercentage.Value && deterministicHashCodeKey != IMapping.GetDeterministicHashCodeKeyValue(locationDigits, id, face.Location.NormalizedPixelPercentage.Value)) continue; collection.Add(face); } if (collection.Count != 1) throw new Exception(); foreach (Models.Face face in collection) { directoryName = Path.GetDirectoryName(file); if (string.IsNullOrEmpty(directoryName)) continue; checkFile = Path.Combine(directoryName, $"{deterministicHashCodeKey}{extensionLowered}.json"); if (File.Exists(checkFile)) continue; json = JsonSerializer.Serialize(face.FaceEncoding); _ = IPath.WriteAllText(checkFile, json, updateDateWhenMatches: false, compareBeforeWrite: true, updateToWhenMatches: null); } } private static (int?, int?, double?) GetReversedDeterministicHashCodeKeysFromSegments(int locationDigits, bool keyValuePairsAny, Dictionary> keyValuePairs, string file, string[] segments) { double? result; if (segments.Length != 3) throw new Exception(); string id = segments[0]; int normalizedPixelPercentageValue; string normalizedPixelPercentage = segments[1]; if (!int.TryParse(id, out int idValue) | !int.TryParse(normalizedPixelPercentage, out normalizedPixelPercentageValue)) result = null; else { result = IMapping.GetDeterministicHashCodeKeyValue(locationDigits, idValue, normalizedPixelPercentageValue); if (keyValuePairsAny && keyValuePairs.ContainsKey(idValue)) UseKeyValuePairsSaveFaceEncoding(locationDigits, keyValuePairs, file, idValue, normalizedPixelPercentageValue, result.Value, $".{segments[2]}"); } return new(idValue, normalizedPixelPercentageValue, result); } internal static (int?, int?) GetReversedDeterministicHashCodeKey(int locationDigits, bool keyValuePairsAny, Dictionary> keyValuePairs, string file) { int? id; int? normalizedPixelPercentage; string fileName = Path.GetFileName(file); if (fileName.Length < 2 || fileName[1..].Contains('-')) { id = null; normalizedPixelPercentage = null; } else { string[] segments = fileName.Split('.'); (id, normalizedPixelPercentage, double? result) = GetReversedDeterministicHashCodeKeysFromSegments(locationDigits, keyValuePairsAny, keyValuePairs, file, segments); if (result is null) { id = null; normalizedPixelPercentage = null; } } return new(id, normalizedPixelPercentage); } }