// 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; namespace osu.Game.Database { public class RealmWrapper : IEquatable> where T : RealmObject, IHasGuidPrimaryKey { public Guid ID { get; } private readonly ThreadLocal threadValues; public readonly IRealmFactory ContextFactory; public RealmWrapper(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 RealmWrapper WrapChild(Func lookup) where TChild : RealmObject, IHasGuidPrimaryKey => new RealmWrapper(lookup(Get()), ContextFactory); public void PerformUpdate(Action perform) { using (ContextFactory.GetForWrite()) perform(this); } // ReSharper disable once CA2225 public static implicit operator T(RealmWrapper wrapper) => wrapper?.Get().Detach(); // ReSharper disable once CA2225 public static implicit operator RealmWrapper(T obj) => obj.WrapAsUnmanaged(); public bool Equals(RealmWrapper other) => other != null && other.ID == ID; public override string ToString() => Get().ToString(); } }