TourIAm/TIAMWebApp/Shared/Utility/SignalRDataSource.cs

642 lines
21 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using AyCode.Core.Enums;
using AyCode.Core.Extensions;
using AyCode.Core.Interfaces;
using AyCode.Services.SignalRs;
using TIAM.Services;
using TIAMWebApp.Shared.Application.Services;
namespace TIAMWebApp.Shared.Application.Utility
{
public class TrackingItem<T>(TrackingState trackingState, T currentValue, T? originalValue = null) where T : class, IId<Guid>
{
public TrackingState TrackingState { get; internal set; } = trackingState;
public T CurrentValue { get; internal set; } = currentValue;
public T? OriginalValue { get; init; } = originalValue; //originalValue == null ? null : TrackingItemHelpers.Clone(originalValue);
internal TrackingItem<T> UpdateItem(TrackingState trackingState, T newValue)
{
CurrentValue = newValue;
if (TrackingState != TrackingState.Add)
TrackingState = trackingState;
return this;
}
}
public class ChangeTracking<T> where T : class, IId<Guid>
{
private readonly List<TrackingItem<T>> _trackingItems = []; //TODO: Dictionary... - J.
internal TrackingItem<T>? AddTrackingItem(TrackingState trackingState, T newValue, T? originalValue = null)
{
if (newValue.Id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(newValue), $@"currentValue.Id.IsNullOrEmpty()");
var itemIndex = _trackingItems.FindIndex(x => x.CurrentValue.Id == newValue.Id);
TrackingItem<T>? trackingItem = null;
if (itemIndex > -1)
{
trackingItem = _trackingItems[itemIndex];
if (trackingState == TrackingState.Remove && trackingItem.TrackingState == TrackingState.Add)
{
_trackingItems.RemoveAt(itemIndex);
return null;
}
return trackingItem.UpdateItem(trackingState, newValue);
}
if (originalValue != null && Equals(newValue, originalValue))
originalValue = TrackingItemHelpers.ReflectionClone(originalValue);
trackingItem = new TrackingItem<T>(trackingState, newValue, originalValue);
_trackingItems.Add(trackingItem);
return trackingItem;
}
public int Count => _trackingItems.Count;
internal void Clear() => _trackingItems.Clear();
public List<TrackingItem<T>> ToList() => _trackingItems.ToList();
public bool TryGetTrackingItem(Guid id, [NotNullWhen(true)] out TrackingItem<T>? trackingItem)
{
trackingItem = _trackingItems.FirstOrDefault(x => x.CurrentValue.Id == id);
return trackingItem != null;
}
internal void Remove(TrackingItem<T> trackingItem) => _trackingItems.Remove(trackingItem);
}
[Serializable]
[DebuggerDisplay("Count = {Count}")]
public class SignalRDataSource<T> : IList<T>, IList, IReadOnlyList<T> where T : class, IId<Guid>
{
private readonly object _syncRoot = new();
protected readonly List<T> InnerList = []; //TODO: Dictionary??? - J.
protected readonly ChangeTracking<T> TrackingItems = new();
protected readonly Guid? ContextId;
protected readonly AcSignalRClientBase SignalRClient;
protected readonly SignalRCrudTags SignalRCrudTags;
public SignalRDataSource(AcSignalRClientBase signalRClient, SignalRCrudTags signalRCrudTags, Guid? contextId = null, bool autoLoadDataSource = true)
{
ContextId = contextId;
SignalRCrudTags = signalRCrudTags;
SignalRClient = signalRClient;
if (autoLoadDataSource) LoadDataSource(false);
}
public bool IsSynchronized => true;
public object SyncRoot => _syncRoot;
public bool IsFixedSize => false;
/// <summary>
/// GetAllMessageTag
/// </summary>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="NullReferenceException"></exception>
public void LoadDataSource(bool clearChangeTracking = true)
{
if (SignalRCrudTags.GetAllMessageTag == SignalRTags.None) throw new ArgumentException($"SignalRCrudTags.GetAllMessageTag == SignalRTags.None");
lock (_syncRoot)
{
var resultList = SignalRClient.GetAllAsync<List<T>>(SignalRCrudTags.GetAllMessageTag, ContextId).GetAwaiter().GetResult() ?? throw new NullReferenceException();
Clear(clearChangeTracking);
InnerList.AddRange(resultList);
}
}
public T? LoadItem(Guid id)
{
if (SignalRCrudTags.GetItemMessageTag == SignalRTags.None) throw new ArgumentException($"SignalRCrudTags.GetItemMessageTag == SignalRTags.None");
T? resultitem = null;
lock (_syncRoot)
{
resultitem = SignalRClient.GetByIdAsync<T>(SignalRCrudTags.GetItemMessageTag, id).GetAwaiter().GetResult();
if (resultitem == null) return null;
if (TryGetIndex(id, out var index)) InnerList[index] = resultitem;
else InnerList.Add(resultitem);
}
return resultitem;
}
/// <summary>
/// set: UpdateMessageTag
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public T this[int index]
{
get
{
if ((uint)index >= (uint)Count) throw new ArgumentOutOfRangeException(nameof(index));
lock (_syncRoot)
{
return InnerList[index];
}
}
set
{
lock (_syncRoot)
{
Update(index, value);
}
}
}
/// <summary>
/// AddMessageTag
/// </summary>
/// <param name="newValue"></param>
/// <exception cref="ArgumentException"></exception>
public void Add(T newValue)
{
if (newValue.Id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(newValue), @"Add->newValue.Id.IsNullOrEmpty()");
lock (_syncRoot)
{
if (Contains(newValue))
throw new ArgumentException($@"It already contains this Id! Id: {newValue.Id}", nameof(newValue));
UnsafeAdd(newValue);
}
}
/// <summary>
/// AddMessageTag or UpdateMessageTag
/// </summary>
/// <param name="newValue"></param>
/// <returns></returns>
public T AddOrUpdate(T newValue)
{
if (newValue.Id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(newValue), @"AddOrUpdate->newValue.Id.IsNullOrEmpty()");
lock (_syncRoot)
{
var index = IndexOf(newValue);
return index > -1 ? Update(index, newValue) : UnsafeAdd(newValue);
}
}
//public void AddRange(IEnumerable<T> collection)
//{
// lock (_syncRoot)
// {
// }
//}
protected T UnsafeAdd(T newValue)
{
TrackingItems.AddTrackingItem(TrackingState.Add, newValue);
InnerList.Add(newValue);
return newValue;
}
/// <summary>
/// AddMessageTag
/// </summary>
/// <param name="index"></param>
/// <param name="newValue"></param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="NullReferenceException"></exception>
public void Insert(int index, T newValue)
{
if (newValue.Id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(newValue), @"Insert->newValue.Id.IsNullOrEmpty()");
lock (_syncRoot)
{
if (Contains(newValue))
throw new ArgumentException($@"It already contains this Id! Id: {newValue.Id}", nameof(newValue));
TrackingItems.AddTrackingItem(TrackingState.Add, newValue);
InnerList.Insert(index, newValue);
}
}
/// <summary>
/// UpdateMessageTag
/// </summary>
/// <param name="newItem"></param>
public T Update(T newItem) => Update(IndexOf(newItem), newItem);
/// <summary>
/// UpdateMessageTag
/// </summary>
/// <param name="index"></param>
/// <param name="newValue"></param>
/// /// <exception cref="ArgumentException"></exception>
/// /// <exception cref="NullReferenceException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public T Update(int index, T newValue)
{
if (default(T) != null && newValue == null) throw new NullReferenceException(nameof(newValue));
if (newValue.Id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(newValue), @"Update->newValue.Id.IsNullOrEmpty()");
if ((uint)index >= (uint)Count) throw new ArgumentOutOfRangeException(nameof(index));
lock (_syncRoot)
{
var currentItem = InnerList[index];
if (currentItem.Id != newValue.Id)
throw new ArgumentException($@"currentItem.Id != item.Id! Id: {newValue.Id}", nameof(newValue));
TrackingItems.AddTrackingItem(TrackingState.Update, newValue, currentItem);
InnerList[index] = newValue;
return newValue;
}
}
/// <summary>
/// RemoveMessageTag
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Remove(T item)
{
lock (_syncRoot)
{
var index = IndexOf(item);
if (index < 0) return false;
RemoveAt(index);
return true;
}
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <returns></returns>
public bool TryRemove(Guid id, out T? item)
{
lock (_syncRoot)
{
return TryGetValue(id, out item) && Remove(item);
}
}
/// <summary>
/// RemoveMessageTag
/// </summary>
/// <param name="index"></param>
/// <exception cref="ArgumentException"></exception>
/// /// <exception cref="ArgumentNullException"></exception>
/// <exception cref="NullReferenceException"></exception>
public void RemoveAt(int index)
{
lock (_syncRoot)
{
var currentItem = InnerList[index];
if (currentItem.Id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(currentItem), $@"RemoveAt->item.Id.IsNullOrEmpty(); index: {index}");
TrackingItems.AddTrackingItem(TrackingState.Remove, currentItem, currentItem);
InnerList.RemoveAt(index);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<TrackingItem<T>> GetTrackingItems()
{
lock (_syncRoot)
return TrackingItems.ToList();
}
public void SetTrackingStateToUpdate(T item)
{
if (TrackingItems.TryGetTrackingItem(item.Id, out var trackingItem))
{
if (trackingItem.TrackingState != TrackingState.Add)
trackingItem.TrackingState = TrackingState.Update;
return;
}
TrackingItems.AddTrackingItem(TrackingState.Update, item, item);
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="trackingItem"></param>
/// <returns></returns>
public bool TryGetTrackingItem(Guid id, [NotNullWhen(true)] out TrackingItem<T>? trackingItem)
{
lock (_syncRoot)
return TrackingItems.TryGetTrackingItem(id, out trackingItem);
}
/// <summary>
///
/// </summary>
/// <returns>Unsaved items</returns>
public bool SaveChanges(out List<TrackingItem<T>> unsavedItems)
{
lock (_syncRoot)
{
foreach (var trackingItem in TrackingItems.ToList())
{
try
{
SaveTrackingItemUnsafe(trackingItem);
}
catch
{
// ignored
}
}
unsavedItems = TrackingItems.ToList();
return unsavedItems.Count == 0;
}
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="resultItem"></param>
/// <returns></returns>
public bool TrySaveItem(Guid id, [NotNullWhen(true)] out T? resultItem)
{
resultItem = null;
if (TryGetTrackingItem(id, out var trackingItem))
resultItem = SaveTrackingItemUnsafe(trackingItem);
return resultItem != null;
}
public bool TrySaveItem(Guid id, TrackingState trackingState, [NotNullWhen(true)] out T? resultItem)
=> TryGetValue(id, out resultItem) && TrySaveItem(resultItem, trackingState, out resultItem);
public bool TrySaveItem(T item, TrackingState trackingState, [NotNullWhen(true)] out T? resultItem)
{
resultItem = SaveItemUnsafe(item, trackingState);
return resultItem != null;
}
protected T? SaveTrackingItemUnsafe(TrackingItem<T> trackingItem)
=> SaveItemUnsafe(trackingItem.CurrentValue, trackingItem.TrackingState);
protected T? SaveItemUnsafe(T item, TrackingState trackingState)
{
var messageTag = SignalRCrudTags.GetMessageTagByTrackingState(trackingState);
if (messageTag == SignalRTags.None) return null; //throw new ArgumentException($"messageTag == SignalRTags.None");
var result = SignalRClient.PostDataAsync(messageTag, item).GetAwaiter().GetResult();
if (result == null) return null; //throw new NullReferenceException($"result == null");
if (TryGetTrackingItem(item.Id, out var trackingItem))
TrackingItems.Remove(trackingItem);
if (TryGetIndex(result.Id, out var index))
InnerList[index] = result;
return result;
}
protected void RollbackItemUnsafe(TrackingItem<T> trackingItem)
{
if (TryGetIndex(trackingItem.CurrentValue.Id, out var index))
{
if (trackingItem.TrackingState == TrackingState.Add) InnerList.RemoveAt(index);
else InnerList[index] = trackingItem.OriginalValue!;
}
else if (trackingItem.TrackingState != TrackingState.Add)
InnerList.Add(trackingItem.OriginalValue!);
TrackingItems.Remove(trackingItem);
}
public bool TryRollbackItem(Guid id, out T? originalValue)
{
lock (_syncRoot)
{
if (TryGetTrackingItem(id, out var trackingItem))
{
originalValue = trackingItem.OriginalValue;
RollbackItemUnsafe(trackingItem);
return true;
}
originalValue = null;
return false;
}
}
public void Rollback()
{
lock (_syncRoot)
{
foreach (var trackingItem in TrackingItems.ToList())
RollbackItemUnsafe(trackingItem);
}
}
public int Count
{
get
{
lock (_syncRoot) return InnerList.Count;
}
}
public void Clear() => Clear(true);
public void Clear(bool clearChangeTracking)
{
lock (_syncRoot)
{
if (clearChangeTracking) TrackingItems.Clear();
InnerList.Clear();
}
}
public int IndexOf(Guid id)
{
lock (_syncRoot)
return InnerList.FindIndex(x => x.Id == id);
}
public int IndexOf(T item) => IndexOf(item.Id);
public bool TryGetIndex(Guid id, out int index) => (index = IndexOf(id)) > -1;
public bool Contains(T item) => IndexOf(item) > -1;
public bool TryGetValue(Guid id, [NotNullWhen(true)] out T? item)
{
lock (_syncRoot)
{
item = InnerList.FirstOrDefault(x => x.Id == id);
return item != null;
}
}
public void CopyTo(T[] array) => CopyTo(array, 0);
public void CopyTo(T[] array, int arrayIndex)
{
lock (_syncRoot) InnerList.CopyTo(array, arrayIndex);
}
public int BinarySearch(int index, int count, T item, IComparer<T>? comparer)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (Count - index < count)
throw new ArgumentException("Invalid length");
lock (_syncRoot)
return InnerList.BinarySearch(index, count, item, comparer);
}
public int BinarySearch(T item) => BinarySearch(0, Count, item, null);
public int BinarySearch(T item, IComparer<T>? comparer) => BinarySearch(0, Count, item, comparer);
public IEnumerator<T> GetEnumerator()
{
lock (_syncRoot)
return InnerList.ToList().GetEnumerator();
}
public ReadOnlyCollection<T> AsReadOnly() => new(this);
private static bool IsCompatibleObject(object? value) => (value is T) || (value == null && default(T) == null);
#region IList, ICollection
bool IList.IsReadOnly => false;
object? IList.this[int index]
{
get => this[index];
set
{
if (default(T) != null && value == null) throw new NullReferenceException(nameof(value));
try
{
this[index] = (T)value!;
}
catch (InvalidCastException)
{
throw new InvalidCastException(nameof(value));
}
}
}
int IList.Add(object? item)
{
if (default(T) != null && item == null) throw new NullReferenceException(nameof(item));
try
{
Add((T)item!);
}
catch (InvalidCastException)
{
throw new InvalidCastException(nameof(item));
}
return Count - 1;
}
void IList.Clear() => Clear(true);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
bool IList.Contains(object? item) => IsCompatibleObject(item) && Contains((T)item!);
int IList.IndexOf(object? item) => (IsCompatibleObject(item)) ? IndexOf((T)item!) : -1;
void IList.Insert(int index, object? item)
{
if (default(T) != null && item == null) throw new NullReferenceException(nameof(item));
try
{
Insert(index, (T)item!);
}
catch (InvalidCastException)
{
throw new InvalidCastException(nameof(item));
}
}
void IList.Remove(object? item)
{
if (IsCompatibleObject(item)) Remove((T)item!);
}
void ICollection<T>.Clear() => Clear(true);
void ICollection.CopyTo(Array array, int arrayIndex)
{
if ((array != null) && (array.Rank != 1))
{
throw new ArgumentException();
}
try
{
lock (_syncRoot)
{
//TODO: _list.ToArray() - ez nem az igazi... - J.
Array.Copy(InnerList.ToArray(), 0, array!, arrayIndex, InnerList.Count);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArrayTypeMismatchException();
}
}
int ICollection.Count => Count;
int ICollection<T>.Count => Count;
bool ICollection<T>.IsReadOnly => false;
void IList<T>.RemoveAt(int index) => RemoveAt(index);
int IReadOnlyCollection<T>.Count => Count;
#endregion IList, ICollection
}
}