﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BasketPrototype.Models
{
    public class BasketWrapper : IBasketWrapper
    {
        private readonly Basket _basket;
        private readonly IBasketRepository _basketRepository;

        public BasketWrapper(Basket basket, IBasketRepository basketItemRepository)
        {
            _basket = basket;
            _basketRepository = basketItemRepository;
        }

        public Guid BasketId => _basket.BasketId;

        public IEnumerable<BasketItem> GetBasketItems()
        {
            return _basketRepository.GetBasketItems(_basket.BasketId);
        }

        public void AddItem(Product product, int quantity)
        {
            var existingItem = _basketRepository.GetBasketItems(_basket.BasketId).SingleOrDefault(item => item.Product.ProductId == product.ProductId);
            if (existingItem == null)
            {
                _basketRepository.AddBasketItem(_basket.BasketId, 
                    new BasketItem
                    {
                        Product = product,
                        Quantity = quantity
                    });
            }
            else
            {
                existingItem.Quantity += quantity;
                _basketRepository.UpdateBasketItem(existingItem);
            }
        }

        public void RemoveItem(Product product)
        {
            _basketRepository.RemoveBasketItemByProductId(_basket.BasketId, product.ProductId);
        }

        public void Clear()
        {
            _basketRepository.Clear(_basket.BasketId);
        }

        public static async Task<BasketWrapper> GetBasketAsync(IServiceProvider services)
        {
            var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
            var currentUser = services.GetRequiredService<IHttpContextAccessor>().HttpContext.User;
            var basketRepository = services.GetRequiredService<IBasketRepository>();
            var applicationUser = await userManager.GetUserAsync(currentUser);
            var basket = basketRepository.GetBasket(applicationUser.UserId);

            return new BasketWrapper(basket, basketRepository);
        }
    }
}
