using MediatR;
using Microsoft.EntityFrameworkCore;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Infrastructure.Data;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Sledgemapper.Api.Handlers
{
    public class InvitePlayerToCampaignCommandHandler : IRequestHandler<InvitePlayerToCampaignCommand, bool>
    {
        private readonly IMediator _mediator;
        private readonly SledgemapperDbContext _dbcontext;

        public InvitePlayerToCampaignCommandHandler(IMediator mediator, SledgemapperDbContext dbcontext)
        {
            _mediator = mediator;
            _dbcontext = dbcontext;
        }

        public async Task<bool> Handle(InvitePlayerToCampaignCommand command, CancellationToken cancellationToken)
        {
            try
            {
                var user = await _dbcontext.Users.FindAsync(command.UserId);

                var campaign = await _dbcontext.Campaigns.Where(campaign=>campaign.CampaignName==command.CampaignName && campaign.OwnerId==command.UserId).Include(campaign=>campaign.InvitedUsers).FirstAsync();
                var invitedUser = await _dbcontext.Users.FirstOrDefaultAsync(user=>user.Email==command.Email);
                _dbcontext.Attach(invitedUser);
                _dbcontext.Attach(campaign);
                campaign.InvitedUsers.Add(invitedUser);
                _dbcontext.Campaigns.Update(campaign);
                await _dbcontext.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
            }
            return false;
        }
    }
}