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

using System;
using CommunityServer.Configuration;

namespace CommunityServer.Components
{

	/// <summary>
	/// The ApplicationKeyProvider enables custom sites or configurations to change how and where 
	/// the ApplicationKey is loaded from. 
	/// 
	/// If the provider is not found, a default one will be loaded. By default we use the config override and 
	/// then check the querystring.
	/// </summary>
	public class ApplicationKeyProvider
	{
		/// <summary>
		/// Key used in the cs.config file
		/// </summary>
		private static readonly string ApplicationKeyProviderKey = "ApplicationKeyProvider";

		/// <summary>
		/// Holds the singleton instance
		/// </summary>
		private static readonly ApplicationKeyProvider apk = null;

		/// <summary>
		/// Load a lazy singleton instance.
		/// </summary>
		static ApplicationKeyProvider()
		{
			CSConfiguration config = CSConfiguration.GetConfig();
			Provider provider = config.Providers[ApplicationKeyProviderKey] as Provider;
			if(provider != null)
			{
				if(Globals.IsNullorEmpty(provider.Type))
					throw new Exception("ApplicationKeyProvider provider found, but no type attribute was specified");

				Type type = Type.GetType(provider.Type);
				if(type == null)
					throw new Exception(string.Format("ApplicationKey Provider Type {0} could not be loaded",provider.Type));

				apk = Activator.CreateInstance(type) as ApplicationKeyProvider;
				if(apk == null)
					throw new Exception("ApplicationKeyProvider could not be loaded from the type " + provider.Type);
			}

			if(apk == null)
				apk = new ApplicationKeyProvider();
		}

		/// <summary>
		/// Singleton Instance
		/// </summary>
		/// <returns></returns>
		public static ApplicationKeyProvider Instance()
		{
			return apk;
		}

		public ApplicationKeyProvider(){}


		/// <summary>
		/// First checks the Config.ApplicationKeyOverride. If null, we will use the QueryString["App"] value.
		/// </summary>
		/// <returns></returns>
		public virtual string GetKey()
		{
			//NOTE: Dan has suggested changing the order here. Any thoughts?

			CSContext context = CSContext.Current;
			string appKey = Globals.UrlEncode(context.QueryString["App"]);

			if(Globals.IsNullorEmpty(appKey))
				appKey = context.Config.ApplicationKeyOverride;

			return appKey;
		}
	}
}
