using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Villain.Databases
{
	public static class DatabaseManager
	{
		private static Dictionary<string, object> _databases = new Dictionary<string, object>();

		public static Action<string> OnClosed;

		public static void Add<TDatabase>(string key, TDatabase value) where TDatabase : SQLServer
		{
			if (value is SQLServer)
			{
				value.OnStateChange = (state) =>
				{
					if (state == ConnectionState.Closed)
					{
						Closed(key);
					}
				};
			}

			_databases.Add(key, value);
		}

		public static TDatabase Get<TDatabase>(string key) where TDatabase : SQLServer
		{
			return (TDatabase)_databases[key];
		}

		public static void Close()
		{
			foreach (object database in _databases)
			{
				if (database is SQLServer)
				{
					((SQLServer)database).Dispose();
				}
			}
		}

		public static void Closed(string key)
		{
			OnClosed?.Invoke(key);
		}
	}
}