using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using ImageBlockz.Core;
using ImageBlockz.Api;

namespace ImageBlockz.Core
{
    /// <summary>
    /// This class provides automatic creating  of instances of IOperation from all plugins.
    /// </summary>
    public class OperationFactory
    {
        private static OperationFactory factory;

        /// <summary>
        /// This method returns default operation factory if exist, otherwise creates new factory.
        /// </summary>
        /// <returns>Default operation factory.</returns>
        public static OperationFactory GetDefaultFactory()
        {
            if (factory == null)
            {
                factory = new OperationFactory();
            }

            return factory;
        }

        private Dictionary<string, Type> plugins = new Dictionary<string, Type>();

        /// <summary>
        /// Create operation with <see cref="string"/> name.
        /// </summary>
        /// <param name="name">Name of Operation.</param>
        /// <returns></returns>
        public IOperation CreateOperation(string name)
        {
            IOperation operation = null;

            Type type;
            if (plugins.TryGetValue(name, out type))
            {
                operation = (IOperation) type.GetConstructor(Type.EmptyTypes).Invoke(null);
            }

            return operation;
        }

        /// <summary>
        /// Register instances of IOperation to dictionary of plugin operations.
        /// </summary>
        /// <param name="name">Name of operation.</param>
        /// <param name="type">Type of operation.</param>
        public void RegisterOperation(string name, Type type)
        {
            if (typeof(IOperation).IsAssignableFrom(type))
            {
                plugins.Add(name, type);
            }
        }
    }
}
