using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using ImageBlockz.Api;

namespace ImageBlockz.Core
{
    /// <summary>
    /// Class, that provides loading of plugins. 
    /// Plugin contains entrypoint file, files with operation and can contains user controls. 
    /// Plugins serve for application functionality expansion.
    /// </summary>
    public class PluginLoader
    {
        /// <summary>
        /// Load plugin from filename and path.
        /// </summary>
        /// <param name="path">Filename of plugin.</param>
        public static void Load(string path)
        {
            Assembly assembly;

            try
            {
                path = Path.GetFullPath(path);
                assembly = Assembly.LoadFile(path);
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.StackTrace);
                return;
            }

            Type[] types = assembly.GetTypes();

            foreach (Type type in types)
            {
                if (typeof(IEntryPoint).IsAssignableFrom(type))
                {
                    IEntryPoint entryPoint = (IEntryPoint) type.GetConstructor(Type.EmptyTypes).Invoke(null);

                    LoadPlugins(entryPoint);
                }
            }
        }

        private static void LoadPlugins(IEntryPoint entryPoint)
        {
            foreach (OperationInfo info in entryPoint.GetOperationInfo())
            {
                LoadOperation(info.OperationType);

                LoadControl(info);

            }
        }

        private static void LoadOperation(Type type)
        {
            OperationFactory.GetDefaultFactory().RegisterOperation(type.FullName, type);
        }

        private static void LoadControl(OperationInfo info)
        {
            ControlFactory.GetDefaultFactory().AddOperationInfo(info);
        }
    }
}
