﻿using Onychophora.Domain.Interfaces;
using Onychophora.Infra.Data.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;

namespace Onychophora.Infra.Data.Repositories
{
    public class RepositoryBase<TEntity> : IDisposable, IRepositoryBase<TEntity> where TEntity : class
    {
        protected OnychophoraContext Db = new OnychophoraContext();

        public void Add(TEntity obj)
        {
            Db.Set<TEntity>().Add(obj);
            Db.SaveChanges();
        }

        public void AddMany(IEnumerable<TEntity> collection)
        {
            Db.Set<TEntity>().AddRange(collection);
            Db.SaveChanges();
        }

        public IEnumerable<TEntity> GetAll()
        {
            return Db.Set<TEntity>().ToList();
        }

        public TEntity GetById(int id)
        {
            return Db.Set<TEntity>().Find(id);
        }

        public void Remove(TEntity obj)
        {
            Db.Set<TEntity>().Remove(obj);
            Db.SaveChanges();
        }

        public void Update(TEntity obj)
        {
            Db.Entry(obj).State = EntityState.Modified;
            Db.SaveChanges();
        }

        public void Dispose()
        {
            if (Db != null)
            {
                Db.Dispose();
            }

            GC.SuppressFinalize(this);
        }
    }
}
