// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Threading; using Realms; #nullable enable namespace osu.Game.Database { public class Live : IEquatable> where T : RealmObject, IHasGuidPrimaryKey { public Guid ID { get; } private readonly ThreadLocal threadValues; public readonly IRealmFactory ContextFactory; public Live(T original, IRealmFactory contextFactory) { ContextFactory = contextFactory; ID = original.Guid; var originalContext = original.Realm; threadValues = new ThreadLocal(() => { var context = ContextFactory.Get(); if (context == null || originalContext?.IsSameInstance(context) != false) return original; return context.Find(ID); }); } public T Get() => threadValues.Value; public Live WrapChild(Func lookup) where TChild : RealmObject, IHasGuidPrimaryKey => new Live(lookup(Get()), ContextFactory); public void PerformUpdate(Action perform) { using (ContextFactory.GetForWrite()) perform(Get()); } public static implicit operator T?(Live? wrapper) => wrapper?.Get().Detach(); public static implicit operator Live(T obj) => obj.WrapAsUnmanaged(); public bool Equals(Live? other) => other != null && other.ID == ID; public override string ToString() => Get().ToString(); } }