﻿using GameTimeApp.Core.Models;
using GameTimeApp.Core.Repositories;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace GameTimeApp.Persistence.Repositories
{
    internal class UserRepository : IUserRepository
    {
        private readonly UserManager<ApplicationUser> _userManager;

        public UserRepository(ApplicationDbContext context)
        {
            _userManager = new UserManager<ApplicationUser>(
                new UserStore<ApplicationUser>(context));
        }

        public int AddPoints(int points, string userId)
        {
            var user = GetApplicationUser(userId);
            if (user == null)
                return 0;

            user.Points += points;
            var div = user.Points / Quest.PointsToCompletion;
            var rem = user.Points % Quest.PointsToCompletion;
            if (div >= 1)
            {
                user.Rewards += div;
                user.Points = rem;
            }
            _userManager.Update(user);
            return div;
        }

        public bool RemoveRewards(int rewards, string userId)
        {
            var user = GetApplicationUser(userId);
            if (user == null)
                return false;

            user.Rewards -= rewards;
            if (user.Rewards < 0)
            {
                user.Rewards = 0;
            }
            _userManager.Update(user);
            return true;
        }

        public ApplicationUser GetApplicationUser(string userId)
        {
            var user = _userManager.FindById(userId);
            return user;
        }
    }
}