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

namespace CSTextEditor
{
    public delegate void CompilerOutputDelegate(string outputLine);
    public class Compiler
    {

        public CSharpCodeProvider codeProvider;

        private static Compiler defaultCompiler;
        public static Compiler DefaultCompiler
        {
            get
            {
                if (defaultCompiler == null)
                {
                    defaultCompiler = new Compiler();
                }
                return defaultCompiler;
            }
        }


        public Compiler()
        {
            codeProvider = new CSharpCodeProvider();
        }

        public CompilerResults Compile(CompilerCode code, CompilerOutputDelegate cod)
        {
            CompilerParameters compileParams = new CompilerParameters();
            compileParams.GenerateExecutable = true;
            compileParams.GenerateInMemory = false;
            compileParams.IncludeDebugInformation = false;
            compileParams.TreatWarningsAsErrors = true;
            compileParams.ReferencedAssemblies.AddRange(code.references);

            CompilerResults results = codeProvider.CompileAssemblyFromSource(compileParams, code.text);

            if (results.Errors.HasErrors)
            {
                cod("-- Compilation of script failed");

                foreach (CompilerError err in results.Errors)
                {
                    cod(err.ToString());
                }
            }
            else
            {
                cod("-- Compilation of script succesfull");
            }
            return results;
        }
    }
}