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

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

        public string Name { get; private set; } = "";

        public override async Task Execute(ExecuteArgs args)
        {
            Name = Name.Trim();
            if (Name.Length == 0)
                return;
            var id = Id.ToObjectId();
            if (id is null)
            {
                return;
            }
            var file =
                await args.Connection.DB.GetFileAsync(id, CancellationToken.None)
                    .ConfigureAwait(false);
            if (file is null)
                return;
            file.Value.Source.ReplaceIndex(Data.IndexSource.Files, id, file.Value.Value.Name,
                Name, file.Value.Value.Confidential, args
            );
            file.Value.Value.Name = Name;
            await file.Value.Source.UpdateFile(file.Value.Value, CancellationToken.None);
            await args.Connection.Send(new Send.FileUpdated(file.Value))
                .ConfigureAwait(false);
        }

        public override void ReadJsonContent(JsonElement json)
        {
            Id = json.GetProperty("id").GetString() ?? "";
            Name = json.GetProperty("name").GetString() ?? "";
        }
    }
}