//
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace MUnique.OpenMU.Persistence;
using System.Text.Json.Serialization;
using MUnique.OpenMU.DataModel.Configuration;
///
/// A reference resolver which uses a to resolve references.
///
public class ByDataSourceReferenceResolver : ReferenceResolver
{
///
/// The data source.
///
private readonly IDataSource _dataSource;
///
/// Initializes a new instance of the class.
///
/// The data source.
public ByDataSourceReferenceResolver(IDataSource dataSource)
{
this._dataSource = dataSource;
}
///
public override void AddReference(string referenceId, object value)
{
// do nothing here, because the data source is the source of truth.
}
///
public override string GetReference(object value, out bool alreadyExists)
{
if (value is IIdentifiable identifiable)
{
alreadyExists = this._dataSource.Get(identifiable.Id) is { };
return identifiable.Id.ToString();
}
alreadyExists = false;
return string.Empty;
}
///
public override object ResolveReference(string referenceId)
{
var id = Guid.Parse(referenceId);
return this._dataSource.Get(id) ?? throw new KeyNotFoundException($"Reference with id '{referenceId}' not found.");
}
}