﻿using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Post_Publisher.Core.Models;
using Post_Publisher.Data.Contexts;

namespace Post_Publisher.Data.Repositories
{
	public interface IUserRepository
	{
		Task<ApplicationUser[]> GetUsers(int skip, int count);

		Task<int> GetUserCount();

		Task<ApplicationUser> GetUserByUserName(string userName);

		Task<ApplicationUser> GetUserById(string id);

		Task SaveChangesAsync();
	}

	public class UserRepository : IUserRepository
	{
		private readonly ApplicationDbContext _db;

		public UserRepository(ApplicationDbContext db)
		{
			_db = db;
		}

		public async Task<ApplicationUser[]> GetUsers(int skip, int count)
		{
			return await _db.Users.OrderBy(x => x.UserName).Skip(skip).Take(count).ToArrayAsync();
		}

		public async Task<int> GetUserCount()
		{
			return await _db.Users.CountAsync();
		}

		public async Task<ApplicationUser> GetUserByUserName(string userName)
		{
			return await _db.Users.FirstOrDefaultAsync(x => x.UserName == userName);
		}

		public async Task<ApplicationUser> GetUserById(string id)
		{
			return await _db.Users.FirstOrDefaultAsync(x => x.Id == id);
		}

		public async Task SaveChangesAsync()
		{
			await _db.SaveChangesAsync();
		}
	}
}
