//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Threading;
using CommunityServer.Components;

namespace CommunityServer.Data
{
	/// <summary>
	/// Summary description for WebSqlProviderHelper.
	/// </summary>
	public class OutOfBoundSqlProviderHelper : ProviderHelper
	{

		#region Member Variables

        private string databaseOwner = "dbo";
        private string connectionString = null;
        const string cacheKey = "OOB.DataProviderKey.SettingsIDs";

		#endregion

		#region Constructor

		public OutOfBoundSqlProviderHelper(string databaseOwner, string connectionString) 
		{
			this.connectionString = connectionString;
			this.databaseOwner = databaseOwner;
		}

		#endregion

		public override int GetSettingsID()
		{
			Hashtable threadsTable = GetThreadsTable();

			// Check if it is in there and return it, else return -1
			if(threadsTable.Contains(Thread.CurrentThread.GetHashCode()))
				return (int)threadsTable[Thread.CurrentThread.GetHashCode()];
			else
				return -1;
		}

		public override void SetSettingsID(int settingsID)
		{
			Hashtable threadsTable = GetThreadsTable();

			// Remove it if it already exists
			if(threadsTable.Contains(Thread.CurrentThread.GetHashCode()))
				threadsTable.Remove(Thread.CurrentThread.GetHashCode());

			// Only add if it is greater than 0 (easy way to remove entries like when a thread is closing)
			if(settingsID > 0)
				threadsTable.Add( Thread.CurrentThread.GetHashCode(), settingsID );
		}

		public override SiteSettings GetSiteSettings()
		{
			return GetSiteSettingsTable()[ GetSettingsID() ] as SiteSettings;
		}


		private Hashtable GetThreadsTable()
		{
			Hashtable threadsTable = CSCache.Get(cacheKey) as Hashtable;
			if(threadsTable == null)
			{
				threadsTable = Hashtable.Synchronized( new Hashtable() );
				CSCache.Max( cacheKey, threadsTable );
			}
			return threadsTable;
		}

		private Hashtable GetSiteSettingsTable()
		{
			Hashtable siteSettingsTable = CSCache.Get(cacheKey + "-Sites") as Hashtable;
			if(siteSettingsTable == null)
			{
				siteSettingsTable = Hashtable.Synchronized( new Hashtable() );

				// Since we can't lookup the sitesettings by the settingsID, and there is no method
				// to get the appName from the settingsID, we'll cache all of them.  Might want to
				// improve this in the future
				ArrayList siteSettings = CommonDataProvider.Instance().LoadAllSiteSettings();
				foreach(SiteSettings site in siteSettings)
					if(!siteSettingsTable.Contains(site.SettingsID))
						siteSettingsTable.Add(site.SettingsID, site);

				CSCache.Insert( cacheKey + "-Sites", siteSettingsTable, CSCache.HourFactor );
			}
			return siteSettingsTable;
		}

	}
}
