using MediatR;
using Sledgemapper.Api.Infrastructure.Data;
using Sledgemapper.Shared.Entities;
using Sledgemapper.Api.Commands;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Sledgemapper.Api.Notifications;

namespace Sledgemapper.Api.Handlers
{
    public class NewLineCommandHandler : IRequestHandler<NewLineCommand, bool>
    {
        private readonly SledgemapperDbContext _dbcontext;

        private readonly IMediator _mediator;

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

        public async Task<bool> Handle(NewLineCommand notification, CancellationToken cancellationToken)
        {
            var jsonString = JsonSerializer.Serialize<Line>(notification.Line);
            var session = _dbcontext.Sessions.First(m => m.SessionName == notification.SessionName);
            _dbcontext.MapLogs.Add(new Sledgemapper.Api.Models.MapLog
            {
                Operation = "N",
                SessionId = session.SessionId,
                Type = "L",
                Timestamp = notification.Timestamp,
                Object = jsonString,
                UserId = notification.UserId,
            });
            await _dbcontext.SaveChangesAsync();
            await _mediator.Publish(new NewLineNotification(session, notification.Line, notification.UserId));
            return true;
        }
    }
}
