using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using InABox.Clients;

namespace InABox.Core
{
    public class MultiSave
    {
        private readonly Dictionary<Type, List<Entity>> _updates = new Dictionary<Type, List<Entity>>();

        public void Clear()
        {
            _updates.Clear();
        }

        public void Add(Type type, params Entity[] entities)
        {
            if (!_updates.ContainsKey(type))
                _updates[type] = new List<Entity>();
            _updates[type].AddRange(entities);
        }

        public void Save(Action<MultiSave>? callback = null, string audittrail = "")
        {
            var tasks = new List<Task>();

            foreach (var type in _updates.Keys)
            {
                var task = Task.Run(
                    () =>
                    {
                        var client = ClientFactory.CreateClient(type);
                        client.Save(_updates[type], audittrail);
                    }
                );
                tasks.Add(task);
            }

            if (callback != null)
                Task.WhenAll(tasks.ToArray()).ContinueWith(t => { callback.Invoke(this); });
            else
                Task.WaitAll(tasks.ToArray());
        }
    }
}