using System;
using System.Collections.Generic;
using System.Reflection;
using Decal.Adapter.Wrappers;

namespace Decal.Adapter;

[CLSCompliant(true)]
public class ViewHandler : IViewHandler, IDisposable
{
	private Dictionary<string, ViewWrapper> myViews;

	private BindingFlags myBindingFlags;

	private PluginHost myHost;

	private bool isDisposed;

	protected bool IsDisposed => isDisposed;

	protected PluginHost Host => myHost;

	public ViewWrapper DefaultView => myViews["Default"];

	public BindingFlags BindingFlags => myBindingFlags;

	public ViewHandler(PluginHost host)
	{
		myBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
		myViews = new Dictionary<string, ViewWrapper>();
		myHost = host;
	}

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

	protected virtual void Dispose(bool disposing)
	{
		if (disposing && myViews != null)
		{
			foreach (ViewWrapper value in myViews.Values)
			{
				value.Dispose();
			}
			myViews.Clear();
			myViews = null;
		}
		isDisposed = true;
	}

	internal void LoadComplete()
	{
		OnLoad();
	}

	protected virtual void OnLoad()
	{
	}

	public void LoadView(string name, string resource)
	{
		myViews.Add(name, Host.LoadViewResource(resource, GetType().Assembly));
	}

	public ViewWrapper GetView(string name)
	{
		if (myViews.TryGetValue(name, out var value))
		{
			return value;
		}
		return null;
	}
}
