using Bp.Sync.BackEnd.Infrastructure.Repositories.Systems;
using Bp.Sync.Dto.Results;
using MediatR;
using Newtonsoft.Json;
using System.Threading;
using System.Threading.Tasks;

namespace Bp.Sync.BackEnd.Application.Commands.Systems.Histories
{
    public class ReadHistoryElasticHandler : IRequestHandler<ReadHistoryElasticCommand, BaseResult>
    {
        private readonly IHistoryElasticRepository _historyElasticRepository;
        public ReadHistoryElasticHandler(IHistoryElasticRepository historyElasticRepository)
        {
            _historyElasticRepository = historyElasticRepository;
        }
        public async Task<BaseResult> Handle(ReadHistoryElasticCommand request, CancellationToken cancellationToken)
        {
            ReadHistoryElasticMess list = JsonConvert.DeserializeObject<ReadHistoryElasticMess>(request.HistoryElastics);

            var history = await _historyElasticRepository.GetById(list.Id);
            if (history != null && history.Id > 0)
            {
                if (history.UpdatedTime.HasValue)
                {
                    var check = System.DateTimeOffset.Now - history.UpdatedTime;
                    if (check.Value.TotalSeconds > 9)
                    {
                        history.ViewTime += list.Time;
                        history.UpdatedTime = System.DateTimeOffset.Now;
                        return await _historyElasticRepository.Add(history);
                    }
                    else
                    {
                        return new BaseResult { Result = Result.Failed, Message = "Dữ liệu bị trùng" };
                    }
                }
                else
                {
                    history.ViewTime += list.Time;
                    history.UpdatedTime = System.DateTimeOffset.Now;
                    return await _historyElasticRepository.Add(history);
                }


            }
            else
                return new BaseResult { Result = Result.Failed, Message = "Không tìm thấy dữ liệu" };
        }
    }
    public class ReadHistoryElasticMess
    {
        public long Id { get; set; } = 0;
        public long Time { get; set; } = 0;
    }
}
