using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Windows.Forms;
using System.Reflection;

namespace Halo3Map.Data
{
    public class pluginCompiler
    {
        public static H3Tag CompileTagPlugin(string TagPath)
        {
            //Create a code provider to do the compile work
            CSharpCodeProvider myCodeProvider = new CSharpCodeProvider();

            //Setup some compiler parameters
            CompilerParameters myCompilerParameters = new CompilerParameters();

            myCompilerParameters.ReferencedAssemblies.Add("System.dll");
            myCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            myCompilerParameters.ReferencedAssemblies.Add(Application.StartupPath + "\\Halo3Map.dll");

            myCompilerParameters.GenerateExecutable = false;
            myCompilerParameters.GenerateInMemory = false;

            //Compile the script
            CompilerResults results = myCodeProvider.CompileAssemblyFromFile(myCompilerParameters, TagPath);

            //Did we get an error?
            if (results.Errors.Count > 0)
            {
                foreach (CompilerError CompErr in results.Errors)
                {
                    MessageBox.Show("Line number " + CompErr.Line +
                        ", Error Number: " + CompErr.ErrorNumber +
                        ", '" + CompErr.ErrorText + ";" +
                        Environment.NewLine + Environment.NewLine);
                }
                return null;
            }

            //Yay no errors!! Now create a instance of our script class     
            H3Tag tag = null;

            foreach(Type t in results.CompiledAssembly.GetTypes() )
            {
                if(t.BaseType == typeof(H3Tag))
                {
                    tag = (H3Tag)Activator.CreateInstance(t);
                    break;
                }
            }

            return tag;
        }

    }
}