#if NETSTANDARD2_0 || NETSTANDARD2_1 || NETCOREAPP
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using FastReport.Code.CodeDom.Compiler;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.VisualBasic;

namespace FastReport.Code.VisualBasic
{
    public class VBCodeProvider : CodeDomProvider
    {
        public override CompilerResults CompileAssemblyFromSource(CompilerParameters cp, string code)
        {
            var codeTree = VisualBasicSyntaxTree.ParseText(code);
            var options = new VisualBasicCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                true,
                optimizationLevel: OptimizationLevel.Release,
                generalDiagnosticOption: ReportDiagnostic.Default);

            var references = new List<MetadataReference>();


            AddReferences(cp, references);

            Compilation compilation = VisualBasicCompilation.Create(
                "_" + Guid.NewGuid().ToString("D"), new[] { codeTree },
                references, options.WithEmbedVbCoreRuntime(true)
            );

            OnBeforeEmitCompilation(compilation);

            using (var ms = new MemoryStream())
            {
                var results = compilation.Emit(ms);
                if (results.Success)
                {
                    var compiledAssembly = Assembly.Load(ms.ToArray());
                    return new CompilerResults(compiledAssembly);
                }

                var result = new CompilerResults();
                foreach (var d in results.Diagnostics)
                    if (d.Severity == DiagnosticSeverity.Error)
                    {
                        var position = d.Location.GetLineSpan().StartLinePosition;
                        result.Errors.Add(new CompilerError
                        {
                            ErrorText = d.GetMessage(),
                            ErrorNumber = d.Id,
                            Line = position.Line,
                            Column = position.Character
                        });
                    }

                return result;
            }
        }

        public override void Dispose()
        {
        }
    }
}
#endif