using Diligent.WebAPI.Business.Interfaces;
using Diligent.WebAPI.Data.Entities;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Diligent.WebAPI.Business.Services
{
    public class CustomerService : ICustomerService
    {
        private readonly UserManager<Customer> _customerManager;

        public CustomerService(UserManager<Customer> customerManager)
        {
            _customerManager = customerManager;
        }

        public async Task<Customer> GetCustomer(string username)
        {
            var customer = await _customerManager.FindByNameAsync(username);
            return customer;
        }

        public async Task<Customer> GetCustomerById(string id)
        {
            var customer = await _customerManager.FindByIdAsync(id);
            return customer;
        }

        public async Task<bool> AddNotification(string receiverId, string roomId)
        {
            var receiver = await GetCustomerById(receiverId);

            if (receiver == null)
            {
                return false;
            }

            var notificationExists = receiver.Notifications.Where(x => x.RoomId == roomId).FirstOrDefault();

            if (notificationExists == null)
            {
                var notification = new Notification
                {
                    Count = 1,
                    RoomId = roomId
                };

                receiver.Notifications.Add(notification);
            }
            else
            {
                notificationExists.Count++;
            }

            await _customerManager.UpdateAsync(receiver);

            return true;
        }

        public async Task<List<Notification>> ReadNotifications(string userId)
        {
            var user = await _customerManager.FindByIdAsync(userId);

            return user.Notifications;
        }

        public async Task<bool> DeleteNotification(string userId, string roomId)
        {
            var user = await GetCustomerById(userId);

            if (user == null)
            {
                return false;
            }

            var notification = user.Notifications.Where(x => x.RoomId == roomId).FirstOrDefault();

            if (notification == null)
            {
                return true;
            }

            user.Notifications.Remove(notification);
            await _customerManager.UpdateAsync(user);

            return true;
        }
    }
}
