using AngleSharp.Dom;
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Application.Common.Extensions;
using EnvelopeGenerator.Application.Common.Query;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Dynamic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace EnvelopeGenerator.Application.Annotations.Commands;
///
///
///
public record CreateAnnotationCommand : EnvelopeReceiverQueryBase, IRequest>
{
///
///
///
public CreateAnnotationCommand()
{
_lazyPSPDFKitInstant = new(() =>
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = null
};
return JsonSerializer.Deserialize(PSPDFKitInstantJSON, options) ?? new ExpandoObject();
});
}
///
///
///
[JsonIgnore]
public string PSPDFKitInstantJSON { get; set; } = null!;
private readonly Lazy _lazyPSPDFKitInstant;
///
///
///
[JsonIgnore]
public ExpandoObject PSPDFKitInstant => _lazyPSPDFKitInstant.Value;
}
///
///
///
public class CreateAnnotationCommandHandler : IRequestHandler>
{
///
///
///
private readonly IRepository _signRepo;
///
///
///
private readonly IRepository _annotRepo;
///
///
///
///
///
public CreateAnnotationCommandHandler(IRepository signRepo, IRepository annotRepo)
{
_signRepo = signRepo;
_annotRepo = annotRepo;
}
///
///
///
///
///
///
public async Task> Handle(CreateAnnotationCommand request, CancellationToken cancel)
{
var query = _signRepo.Query;
#region Envelope Query
if (request.Envelope.Id is int envelopeId)
query = query.Where(annot => annot.Document.EnvelopeId == envelopeId);
if (request.Envelope.Uuid is string envelopeUuid)
query = query.Where(annot => annot.Document.Envelope!.Uuid == envelopeUuid);
#endregion
// Receiver Query
query = query.Where(request.Receiver);
var elements = await query.ToListAsync(cancel);
foreach (var element in elements)
{
var annots = ParsePSPDFKitInstant(request.PSPDFKitInstant, element.Id)
.Select(annot => new Annotation()
{
ElementId = element.Id,
Name = annot.Key,
Value = annot.Value,
AddedWhen = DateTime.UtcNow
});
element.Annotations = await _annotRepo.CreateAsync(annots, cancel);
}
return elements;
}
///
///
///
///
///
///
public static Dictionary ParsePSPDFKitInstant(ExpandoObject instant, int elementId)
{
Dictionary annots = new();
// parse json here
return annots;
}
}