﻿using System.Collections.Generic;
using NHibernate;

namespace DeVi.Models.Repositories
{
	internal abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : class
	{
		public void Add( TEntity entity )
		{
			using( var tx = Session.BeginTransaction() )
			{
				Session.Save( entity );
				tx.Commit();
			}
		}

		public void AddRange( IEnumerable<TEntity> entities )
		{
			using( var tx = Session.BeginTransaction() )
			{
				foreach( var entity in entities )
				{
					Session.Save( entity );
				}

				tx.Commit();
			}
		}

		public void Delete( TEntity entity )
		{
			using( var tx = Session.BeginTransaction() )
			{
				Session.Delete( entity );
				tx.Commit();
			}
		}

		public IEnumerable<TEntity> GetAll()
		{
			return Session.CreateCriteria<TEntity>().List<TEntity>();
		}

		public TEntity GetById( object id )
		{
			return Session.Get<TEntity>( id );
		}

		public void Update( TEntity entity )
		{
			using( var tx = Session.BeginTransaction() )
			{
				Session.Update( entity );
				tx.Commit();
			}
		}

		protected ISession Session => SessionProvider.Session;
	}
}