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

using System;
using CommunityServer.Configuration;

namespace CommunityServer.Components
{
    public sealed class SingletonProviderHelper
    {
        public static object LoadInstance(string  ProviderKey, Type defaultType)
        {
            CSConfiguration config = CSConfiguration.GetConfig();
            Provider provider = config.Providers[ProviderKey] as Provider;
            object obj = null;
            if(provider != null)
            {
                if(Globals.IsNullorEmpty(provider.Type))
                    throw new Exception("Provider '" + provider.Type + "' found, but no type attribute was specified");

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

                obj = Activator.CreateInstance(type);

                return obj;
            }
            else if(defaultType != null)
            {
                obj = Activator.CreateInstance(defaultType);
            }

            if(obj != null)
                return obj;

            throw new Exception("Provider " + ProviderKey + " could not be loaded");

        }
    }
}