﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using ChatSystem.Data.Contracts;
using ChatSystem.Data.Repositories;
using ChatSystem.Models;

namespace ChatSystem.Data
{
    public class ChatSystemData : IChatSystemData
    {
        private readonly Dictionary<Type, object> repositories = new Dictionary<Type, object>();

        public ChatSystemData(DbContext context)
        {
            this.Context = context;
        }

        public DbContext Context { get; private set; }

        public IRepository<User> Users
        {
            get { return this.GetRepository<User>(); }
        }

        public IRepository<Message> Messages
        {
            get { return this.GetRepository<Message>(); }
        }

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

        public int SaveChanges()
        {
            return this.Context.SaveChanges();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (this.Context != null)
            {
                this.Context.Dispose();
            }
        }

        private IRepository<T> GetRepository<T>() where T : class
        {
            if (!this.repositories.ContainsKey(typeof(T)))
            {
                var type = typeof(EfGenericRepository<T>);
                this.repositories.Add(typeof(T), Activator.CreateInstance(type, this.Context));
            }

            return (IRepository<T>)this.repositories[typeof(T)];
        }
    }
}
