using CsvHelper.Configuration; using InABox.Core; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace InABox.Poster.CSV; public interface ICSVClassMap { ClassMap ClassMap { get; } } public interface ICSVClassMap : ICSVClassMap { new ClassMap ClassMap { get; } ClassMap ICSVClassMap.ClassMap => ClassMap; void Map(string name, Expression> expr); } public class CSVClassMap : ClassMap, ICSVClassMap { public ClassMap ClassMap => this; public void Map(string name, Expression> expr) { Map(expr).Name(name); } } public interface ICSVExport : IPostResult where TPostable : IPostable { Type Type { get; } ICSVClassMap ClassMap { get; } IEnumerable Records { get; } } public interface ICSVExport : ICSVExport where TExport : class where TPostable : IPostable { new Type Type => typeof(TExport); new CSVClassMap ClassMap { get; } new IEnumerable Records { get; } Type ICSVExport.Type => Type; ICSVClassMap ICSVExport.ClassMap => ClassMap; IEnumerable ICSVExport.Records => Records; } public class CSVExport : ICSVExport where TExport : class where TPostable : IPostable { public CSVClassMap ClassMap { get; } = new CSVClassMap(); public IEnumerable Records => items.Where(x => x.Item2.PostedStatus == PostedStatus.Posted).Select(x => x.Item1); private List> items = new List>(); private Dictionary>> fragments = new Dictionary>>(); public IEnumerable PostedEntities => items.Select(x => x.Item2); public IEnumerable>>> Fragments => fragments.Select(x => new KeyValuePair>>(x.Key, x.Value)); public void DefineMapping(List>>> mappings) { foreach(var (name, expr) in mappings) { ClassMap.Map(name, expr); } } public void Map(string name, Expression> expr) { ClassMap.Map(name, expr); } public void AddSuccess(TExport export, TPostable postable) { postable.Post(); items.Add(new(export, postable)); } } /// /// Defines an interface for posters that can export to CSV. /// /// [Caption("CSV")] public interface ICSVPoster : IPoster where TEntity : Entity, IPostable, IRemotable, IPersistent, new() { bool BeforePost(IDataModel model); ICSVExport Process(IDataModel model); void AfterPost(IDataModel model, IPostResult result); }