using System;
using System.Collections.Generic;

namespace QCRPG.Framework;

public class GenericValueTypeNotifier<T> : IObservable<T> where T : struct
{
	private List<IObserver<T>> observers = new List<IObserver<T>>();

	public void RegisterObserver(IObserver<T> observer)
	{
		GC.KeepAlive(observers);
		lock (observers)
		{
			if (observers.Contains(observer))
			{
				return;
			}
			observers.Add(observer);
		}
		GC.KeepAlive(observers);
	}

	public void UnregisterObserver(IObserver<T> observer)
	{
		GC.KeepAlive(observers);
		lock (observers)
		{
			if (!observers.Contains(observer))
			{
				return;
			}
			observers.Remove(observer);
		}
		GC.KeepAlive(observers);
	}

	public void NotifyObservers(T arg)
	{
		GC.KeepAlive(observers);
		lock (observers)
		{
			foreach (IObserver<T> observer in observers)
			{
				observer.NotifyObserver(arg);
			}
		}
		GC.KeepAlive(observers);
	}
}
