using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using BlueWest.EfMethods.Extensions; using Microsoft.CodeAnalysis.CSharp; using static BlueWest.EfMethods.Sources.Constants; namespace BlueWest.EfMethods.Sources { internal static class EfMethodsSource { internal static SourceCode Generate(EfMethodsModel model, EfTemplates templates) { using var builder = new SourceBuilder(); builder .WriteLine(GeneratedFilesHeader) .WriteUsings(model.Usings) .WriteLine("using Microsoft.EntityFrameworkCore;") .WriteLine("using System.Linq;") .WriteLine("using System.Linq.Expressions;") .WriteLine("using System.Threading.Tasks;") .WriteLine() // Namespace declaration .WriteLine($"namespace {model.Namespace}") .WriteOpeningBracket() // Class declaration .WriteLine($"public static partial class {model.ContextTypeName}Extensions") .WriteOpeningBracket() .WriteLine(); foreach (var methodModel in model.MethodsModels.OrderBy(x => x.PropertyName)) { switch (methodModel) { case EfAddMethodsModel currentModel: builder .EfAddAddMethod(model, currentModel, templates.AddTemplate) .WriteLine(); break; case EfUpdateMethodsModel currentModel: builder .EfAddUpdateMethod(model, currentModel, templates.UpdateTemplate) .WriteLine(); break; case EfGetOneByModel currentModel: builder .EfAddGetOneEntityByMethod(model, currentModel, templates.GetOneByTemplate) .WriteLine(); break; case EfGetManyModel currentModel: builder .EfAddGetManyMethod(model, currentModel, templates.GetManyTemplate) .WriteLine(); break; case EfGetOneWithModel currentModel: builder .EfAddGetOneMethod(model, currentModel, templates.GetOneTemplate) .WriteLine(); break; case EfGetListModel currentModel: builder .EfAddGetListMethod(model, currentModel, templates.GetListTemplate) .WriteLine(); break; case EfAddToListModel currentModel: builder .EfAddAddToListMethod(model, currentModel, templates.AddToListTemplate) .WriteLine(); break; case EfGetOneFromListModel currentModel: builder .EfAddGetOneFromListMethod(model, currentModel, templates.GetOneFromListTemplate) .WriteLine(); break; } } builder // End class declaration .WriteClosingBracket() .WriteLine() // End namespace declaration .WriteClosingBracket(); var generatedCode = builder.ToString(); var hintName = $"{model.ContextTypeName}Extensions.g.cs"; return new(generatedCode, hintName); } internal static SourceBuilder ParseTemplate(this SourceBuilder builder, string finalTemplate) { string[] array = finalTemplate.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i < array.Length; i++) { var line = array[i]; builder.WriteLine(line); } return builder; } } }