using nft.framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace nft.framework.repository
{
    public class DefaultRepositoryBuilder<S,T,U> : IRepositoryBuilder<S,T> where S: IIdentifier where T: class, IHasNameAndID where U: IRepository<S,T>
    {
        protected Dictionary<S, T> dictionary = new Dictionary<S, T>();

        public void Add(T model)
        {
            dictionary.Add((S)model.ID, model);
        }

        public T RemoveByID(S id)
        {
            T ret;
            if (!dictionary.TryGetValue(id, out ret)) {
                ret = null;
            }            
            dictionary.Remove(id);
            return ret;
        }

        public IRepository<S,T> Finalize()
        {
            Type[] types = { typeof(IDictionary<S, T>) };
            ConstructorInfo ci = typeof(U).GetConstructor(types);
            object[] args = { this.dictionary };
            U repository = (U) ci.Invoke( args );
            return repository;
        }
    }
}
