using System;
using System.Collections.Generic;

namespace CorgiLabs.Utility
{
    /// <summary>
    /// Class implementing the Service Locator pattern in a generic way.
    /// 
    /// This implentation allows for single service per type, thus removing the necessity of having actual Singletons for each of them.
    /// Services must be nullable classes.
    /// </summary>
    public class ServiceLocator
    {
        /// <summary>
        /// Provided services Dictionary.
        /// </summary>
        private static Dictionary<Type, object> m_Services = new Dictionary<Type, object>();

        /// <summary>
        /// Gets a service.
        /// </summary>
        /// <typeparam name="T">Service type.</typeparam>
        /// <returns>A concrete service instance.</returns>
        public static T Get<T>() where T : class
        {
            return m_Services.ContainsKey(typeof(T)) ? m_Services[typeof(T)] as T: null;
        }

        /// <summary>
        /// Registers a service, making it available to any class requiring it.
        /// </summary>
        /// <typeparam name="T">Servie type.</typeparam>
        /// <param name="service">Provided instance.</param>
        public static void Provide<T>(T service) where T : class
        {
            m_Services[typeof(T)] = service;
        }
    }
}
