using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace Dacryptero.Web.Events.Receive
{
    public class FilePersonFetch : ReceiveBase
    {
        public string Person { get; private set; } = "";

        public string? Root { get; private set; }

        public override async Task Execute(ExecuteArgs args)
        {
            var person = Person.ToObjectId();
            var root = Root?.ToObjectId();
            if (person is null)
                return;
            await foreach (var chunk in args.Data
                .EnumerateFilesAsync(person, root, CancellationToken.None)
                .Chunks(10, CancellationToken.None)
                .ConfigureAwait(false)
            )
            {
                await args.Connection.Send(new Send.FilePersonSend(Person, Root, chunk))
                    .ConfigureAwait(false);
            }
        }

        public override void ReadJsonContent(JsonElement json)
        {
            Person = json.GetProperty("person").GetString() ?? "";
            Root = json.TryGetProperty("root", out JsonElement node) ?
                node.GetString() : null;
        }
    }
}