using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF.Framework.Models.Repository.Base;

namespace WPF.Framework.Models.Repository
{
    class Repository<T> : IRepository<T> where T: class, IEntity, new()
    {
        protected readonly AgentsDbContext context;
        public Repository(AgentsDbContext context)
        {
            this.context = context;
        }
        public override IQueryable<T> Items => context.Set<T>();

        public override T Add(T entity)
        {
            if(entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            var result = context.Set<T>().Add(entity);
            context.SaveChanges();
            return result;
        }

        public override T Get(int id)
        {
            return context.Set<T>().SingleOrDefault(entity => entity.ID == id);
        }

        public override void Remove(int id)
        {
            var entity = Get(id) ?? new T() { ID = id };
            context.Set<T>().Remove(entity);
            context.SaveChanges();
        }

        public override void Update(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            var result = Get(entity.ID);
            result = entity;
            context.SaveChanges();
        }
    }
}
