﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleChat.Data
{
    public class UnitOfWork : IUnitOfWork, IDisposable
    {
        private EntDBEntities _entDbContext;
        public UnitOfWork()
        {
            _entDbContext = new EntDBEntities();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _entDbContext.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Commit()
        {
            _entDbContext.SaveChanges();
        }

        public async Task CommitAsync()
        {
            await Task.WhenAll(_entDbContext.SaveChangesAsync());
        }

        #region Repositories

        public IGenericRepository<User> UserRepository
        {
            get
            {
                return new GenericRepository<User>(_entDbContext);
            }
        }

        public IGenericRepository<Room> RoomRepository
        {
            get
            {
                return new GenericRepository<Room>(_entDbContext);
            }
        }

        public IGenericRepository<UserToken> UserTokenRepository
        {
            get
            {
                return new GenericRepository<UserToken>(_entDbContext);
            }
        }

        #endregion

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
