using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; using StabilityMatrix.Core.Models.Database; namespace StabilityMatrix.Core.Models; /// /// Model file union that may be remote or local. /// [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public record HybridModelFile { /// /// Singleton instance of that represents use of a default model. /// public static HybridModelFile Default { get; } = FromRemote("@default"); /// /// Singleton instance of that represents no model. /// public static HybridModelFile None { get; } = FromRemote("@none"); private string? RemoteName { get; init; } public LocalModelFile? Local { get; init; } [MemberNotNullWhen(true, nameof(RemoteName))] [MemberNotNullWhen(false, nameof(Local))] [JsonIgnore] public bool IsRemote => RemoteName != null; [JsonIgnore] public string FileName => IsRemote ? RemoteName : Local.FileName; [JsonIgnore] public string ShortDisplayName { get { if (IsNone) { return "None"; } if (IsDefault) { return "Default"; } return Path.GetFileNameWithoutExtension(FileName); } } public static HybridModelFile FromLocal(LocalModelFile local) { return new HybridModelFile { Local = local }; } public static HybridModelFile FromRemote(string remoteName) { return new HybridModelFile { RemoteName = remoteName }; } public string GetId() { return $"{FileName};{IsNone};{IsDefault}"; } private sealed class RemoteNameLocalEqualityComparer : IEqualityComparer { public bool Equals(HybridModelFile? x, HybridModelFile? y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(y, null)) return false; if (x.GetType() != y.GetType()) return false; return Equals(x.FileName, y.FileName) && x.IsNone == y.IsNone && x.IsDefault == y.IsDefault; } public int GetHashCode(HybridModelFile obj) { return HashCode.Combine(obj.IsNone, obj.IsDefault, obj.FileName); } } /// /// Whether this instance is the default model. /// public bool IsDefault => ReferenceEquals(this, Default); /// /// Whether this instance is no model. /// public bool IsNone => ReferenceEquals(this, None); public static IEqualityComparer Comparer { get; } = new RemoteNameLocalEqualityComparer(); }