﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Hub.Domain.Base;

namespace Hub.Infrastructure.Repository.MSSQL.Base
{
    public abstract class BaseRepository<T> : IRepository<T> where T : class, IEntity
    {
        protected readonly DbSet<T> DbSet;
        protected BaseRepository(DbSet<T> dbSet)
        {
            DbSet = dbSet;
        }

        protected void SaveState()
        {
            var context = DataContext.Instance;
            context.SaveChanges();
        }

        public void Add(T probe)
        {
            DbSet.Add(probe);
            SaveState();
        }

        public void AddRange(IList<T> probes)
        {
            DbSet.AddRange(probes);
            SaveState();
        }

        public bool Exists(T probe)
        {
            return DbSet.Any(b => b.Id == probe.Id);
        }

        public T Get(int id)
        {
            return DbSet.SingleOrDefault(b => b.Id == id);
        }

        public IList<T> GetAll()
        {
            return DbSet.ToList();
        }

        public void Remove(T probe)
        {
            var value = Get(probe.Id);
            if (value != null)
            {
                DbSet.Remove(value);
                SaveState();
            }
        }

        public virtual void MarkAsDeleted(T probe)
        {
            var value = Get(probe.Id);
            if (value != null)
            {
                value.IsActive = false;
                SaveState();
            }
        }
    }
}
