using System;
using System.Collections.Generic;
using Decal.Interop.Inject;

namespace Decal.Adapter.Wrappers;

[CLSCompliant(true)]
public class ViewControls : MarshalByRefObject, IDisposable
{
	private ViewWrapper myParent;

	private Dictionary<string, IControlWrapper> myControls;

	private bool isDisposed;

	[CLSCompliant(false)]
	public IControlWrapper this[string controlName]
	{
		get
		{
			if (myControls.ContainsKey(controlName))
			{
				return myControls[controlName];
			}
			IControlWrapper controlWrapper = ControlRegistry.CreateInstance(myParent[controlName]);
			myControls.Add(controlName, controlWrapper);
			return controlWrapper;
		}
		set
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			myControls[controlName] = value;
			myParent[controlName] = value.Underlying as IControl;
		}
	}

	internal ViewControls(ViewWrapper parent)
	{
		myParent = parent;
		myControls = new Dictionary<string, IControlWrapper>();
	}

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

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

	private void Dispose(bool disposing)
	{
		if (!isDisposed && disposing && myParent != null)
		{
			foreach (IControlWrapper value in myControls.Values)
			{
				if (value is IDisposable disposable)
				{
					disposable.Dispose();
				}
			}
			myParent = null;
		}
		isDisposed = true;
	}
}
