using InABox.Core;
using NPOI.SS.Formula.Functions;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InABox.Poster.Timberline;

public class TimberlinePostResult<TExport, TPostable> : IPostResult<TPostable>
    where TPostable : IPostable
    where TExport : class
{
    private List<Tuple<TPostable, TExport?>> items = new List<Tuple<TPostable, TExport?>>();

    private Dictionary<Type, List<IPostableFragment<TPostable>>> fragments = new Dictionary<Type, List<IPostableFragment<TPostable>>>();

    public IEnumerable<TExport> Exports => items
        .Where(x => x.Item1.PostedStatus == PostedStatus.Posted)
        .NotNull(x => x.Item2);

    public IEnumerable<TPostable> PostedEntities => items.Select(x => x.Item1);

    public IEnumerable<Tuple<TPostable, TExport?>> Items => items;

    public IEnumerable<KeyValuePair<Type, IEnumerable<IPostableFragment<TPostable>>>> Fragments =>
        fragments.Select(x => new KeyValuePair<Type, IEnumerable<IPostableFragment<TPostable>>>(x.Key, x.Value));

    public void AddSuccess(TPostable post, TExport? export)
    {
        post.Post();
        items.Add(new Tuple<TPostable, TExport?>(post, export));
    }

    public void AddFailed(TPostable post, string note)
    {
        post.FailPost(note);
        items.Add(new Tuple<TPostable, TExport?>(post, null));
    }

    public void AddFragment(IPostableFragment<TPostable> fragment)
    {
        if (!fragments.TryGetValue(fragment.GetType(), out var fragmentList))
        {
            fragmentList = new List<IPostableFragment<TPostable>>();
            fragments[fragment.GetType()] = fragmentList;
        }
        fragmentList.Add(fragment);
    }
}
