using System;

namespace Decal.Adapter;

public class DisposableByRefObject : MarshalByRefObject, IDisposable
{
	private bool isDisposed;

	private EventHandler myDisposing;

	public event EventHandler Disposing
	{
		add
		{
			myDisposing = (EventHandler)Delegate.Combine(myDisposing, value);
		}
		remove
		{
			myDisposing = (EventHandler)Delegate.Remove(myDisposing, value);
		}
	}

	internal DisposableByRefObject()
	{
	}

	~DisposableByRefObject()
	{
		Dispose(userCalled: false);
	}

	public void Dispose()
	{
		Dispose(userCalled: true);
		GC.SuppressFinalize(this);
	}

	protected virtual void Dispose(bool userCalled)
	{
		if (!isDisposed && userCalled && myDisposing != null)
		{
			try
			{
				myDisposing(this, new EventArgs());
			}
			catch
			{
			}
		}
		isDisposed = true;
	}

	protected void EnforceDisposedOnce()
	{
		if (isDisposed)
		{
			throw new ObjectDisposedException(GetType().ToString());
		}
	}
}
