using AllocsFixes.CustomCommands;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace AllocsFixes
{
	public class CommandExtensions
	{
		public static void InitCommandExtensions (GameManager manager)
		{
			try {
				ConsoleSdtd cons = manager.m_GUIConsole;
				Type commandType = typeof (ConsoleCommand);

				Mods.ModData thisMd = new Mods.ModData ();
				thisMd.assembly = Assembly.GetExecutingAssembly ();

				List<Mods.ModData> mods = Mods.LoadedMods ();
				mods.Add (thisMd);

				foreach (Mods.ModData md in mods) {
					foreach (Type t in md.assembly.GetTypes()) {
						if (t.IsClass && commandType.IsAssignableFrom (t)) {
							try {
								ConstructorInfo ctor = t.GetConstructor (new Type[] {typeof(ConsoleSdtd)});
								cons.AddCommand ((ConsoleCommand)ctor.Invoke (new object[] {cons}));
							} catch (Exception e) {
								Log.Out ("Could not register custom command \"" + t.Name + "\": " + e);
							}
						}
					}
				}
			} catch (Exception e) {
				Log.Out ("Error registering custom commands: " + e);
			}
		}
	}
}
