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

namespace DraftIt.Data
{
    public class DraftItContext : DbContext, IUnitOfWork
    {
        private readonly Dictionary<Type, IRepository> repositories;

        public DbSet<DraftTemplate> DraftTemplates { get; set; }
        public DbSet<DraftTemplateItem> DraftTemplateItems { get; set; }
        public DbSet<DraftItem> DraftItems { get; set; }
        public DbSet<Draft> Drafts { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<DraftUser> DraftUsers { get; set; }
        public DbSet<DraftPick> DraftPicks { get; set; }

        public DraftItContext() : base("DraftItConnection")
        {
            repositories = GetRepositories();
        }


        public IRepository<T> Get<T>() where T : IEntity
        {
            return (IRepository<T>) repositories[typeof(T)];
        }

        public async Task<int> Save()
        {
            return await SaveChangesAsync();
        }

        public virtual Dictionary<Type, IRepository> GetRepositories()
        {
            return new Dictionary<Type, IRepository> {
                { typeof(DraftTemplate)     , new DbRepository<DraftTemplate>(this) },
                { typeof(DraftTemplateItem) , new DbRepository<DraftTemplateItem>(this) },
                { typeof(DraftItem)         , new DbRepository<DraftItem>(this) },
                { typeof(Draft)             , new DbRepository<Draft>(this) },
                { typeof(User)              , new DbRepository<User>(this) },
                { typeof(DraftUser)         , new DbRepository<DraftUser>(this) },
                { typeof(DraftPick)         , new DbRepository<DraftPick>(this) },
            };
        }
    }
}
