using System ;
using System.Collections.Generic ;


namespace DxLibDLL
{


	public static partial class DX
	{


		public abstract class Handler< THandler > : Disposable where THandler : Handler< THandler > 
		{

			internal static int ToHandle( THandler handler )
			{
				if( handler != null )
				{
					return handler.handle ;
				}
				else
				{
					return -1 ;
				}
			}

			internal static int[] ToHandleArray( THandler[] handlers )
			{
				if( handlers != null )
				{
					int[] handles = new int[ handlers.Length ] ;

					for( int i = 0 ; i < handles.Length ; i ++ )
					{
						handles[ i ] = ToHandle( handlers[ i ] ) ;
					}

					return handles ;
				}
				else
				{
					return null ;
				}
			}

			internal protected override sealed void Destruct()
			{
				handlers.Remove( this.handle ) ;
				this.DestructHandler( this.handle ) ;
			}

			internal protected Handler( int handle ) : base()
			{
				this.handle = handle ;
			}

			internal protected Handler( int handle, bool disposed ) : base( disposed )
			{
				this.handle = handle ;
			}

			internal protected abstract void DestructHandler( int handle ) ;

			private int handle ;

			internal protected static THandler FindHandler( int handle )
			{
				THandler handler ;
				handlers.TryGetValue( handle , out handler ) ;
				return handler ;
			}

			internal protected static void AddHandler( int handle , THandler handler )
			{
				handlers.Add( handle, handler ) ;
			}

			internal protected sealed override void Construct()
			{
				this.handle = -1 ;
			}

			internal static void SuppressDisposeAll()
			{
				foreach( THandler handler in handlers.Values )
				{
					handler.SuppressDispose() ;
				}
			}

			internal static void InitializeAll()
			{
				handlers = new SortedDictionary< int , THandler >() ;
			}

			internal static void FinalizeAll()
			{
				SuppressDisposeAll() ;
				handlers = null ;
			}

			private static SortedDictionary< int , THandler > handlers ;
		}
	}
}
