using System.Collections.Generic;
using System.Linq;
using System.Text;

using DataAccess.Repository.Abstract;

using NHibernate;
using NHibernate.Linq;

namespace DataAccess.NHDal {
	public class NHibernateRepository<T, TId> : IRepository<T, TId> where T : class {
		protected ISession session = null;

		protected ITransaction transaction = null;

		public NHibernateRepository() {
			this.session = NHibernateSessionProvider.SessionFactory.OpenSession();
#if DEBUG
			System.Diagnostics.Trace.WriteLine("NHibernateRepository Itor");
#endif
		}

		public ISession NHibernateSession {
			get {
				return this.session;
			}
		}

		public IQueryable<T> GetList() {
			return (from entity in session.Query<T>() select entity);
		}

		public IQueryable<T> GetList(QueryBase<T> query) {
			return query.SatisfyingElementsFrom(session.Query<T>());
		}

		private void closeTransaction() {
			transaction.Dispose();
			transaction = null;
		}

		private void closeSession() {
			session.Close();
			session.Dispose();
			session = null;
		}

		public void Dispose() {
#if DEBUG
			System.Diagnostics.Trace.WriteLine("NHibernateRepository Dispose");
#endif
			if (session != null) {
				session.Flush(); // commit session transactions
				closeSession();
			}
		}
	}
}
