using MediatR; using Sledgemapper.Api.Commands; using Sledgemapper.Api.Notifications; using Sledgemapper.Api.Infrastructure.Data; using Sledgemapper.Shared.Entities; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using System; using Microsoft.EntityFrameworkCore; namespace Sledgemapper.Api.Handlers { public class NewOverlayCommandHandler : IRequestHandler { private readonly SledgemapperDbContext _dbcontext; private readonly IMediator _mediator; public NewOverlayCommandHandler(IMediator mediator, SledgemapperDbContext dbcontext) { _dbcontext = dbcontext; _mediator = mediator; } public async Task Handle(NewOverlayCommand command, CancellationToken cancellationToken) { var user = await _dbcontext.Users.FindAsync(command.UserId); _dbcontext.Attach(user); var campaign = await _dbcontext.Campaigns.Where(campaign => campaign.CampaignId == command.Campaign && campaign.OwnerId == command.UserId).Include(campaign => campaign.Maps).FirstAsync(); var maps = campaign.Maps.Any(s => s.SessionId == new Guid(command.SessionName)); if (!maps) { throw new Exception("Unauthorized"); } var jsonString = JsonSerializer.Serialize(command.Overlay); var session = _dbcontext.Sessions.First(m => m.SessionId == new Guid(command.SessionName)); _dbcontext.MapLogs.Add(new Models.MapLog { Operation = "N", SessionId = session.SessionId, Type = "O", Timestamp = command.Timestamp, Object = jsonString, UserId = command.UserId, }); await _dbcontext.SaveChangesAsync(); await _mediator.Publish(new NewOverlayNotification(session, command.Overlay, command.UserId)); return true; } } }