using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Decal.Interop.Inject;

namespace Decal.Adapter.Wrappers;

public abstract class ControlWrapperBase<T> : MarshalByRefObject, IControlWrapper, IDisposable where T : class
{
	private T myControl;

	private bool isDisposed;

	[EditorBrowsable(EditorBrowsableState.Never)]
	public object Underlying => myControl;

	public int Id => ((IControl)myControl).ID;

	public int ChildCount => ((IControl)myControl).ChildCount;

	protected bool Disposed => isDisposed;

	protected T Control => myControl;

	~ControlWrapperBase()
	{
		Dispose(disposing: false);
	}

	[EditorBrowsable(EditorBrowsableState.Never)]
	public virtual void Initialize(object control)
	{
		myControl = control as T;
	}

	[EditorBrowsable(EditorBrowsableState.Never)]
	public object ChildById(int id)
	{
		return ((IControl)myControl).get_Child(id, ePositionType.ePositionByID);
	}

	[EditorBrowsable(EditorBrowsableState.Never)]
	public object ChildByIndex(int index)
	{
		return ((IControl)myControl).get_Child(index, ePositionType.ePositionByIndex);
	}

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

	protected virtual void Dispose(bool disposing)
	{
		if (!isDisposed)
		{
		}
		if (myControl != null)
		{
			Marshal.ReleaseComObject(myControl);
			myControl = null;
		}
		isDisposed = true;
	}
}
