using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services.Notifications;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudInfrastructure.Background
{
    /// <summary>
    /// Класс для отправки email
    /// </summary>
    internal class WorkToSendEmail : Work
    {
        private NotificationDto notification;

        public WorkToSendEmail(NotificationDto notification) : base(MakeWorkId(notification))
        {
            this.notification = notification;
        }

        protected override async Task Action(string id, IServiceProvider services, Action<string, double?> onProgressCallback, CancellationToken token)
        {
            var notificationService = services.GetRequiredService<INotificationTransportService>();
            var notificationRepository = services.GetRequiredService<INotificationRepository>();

            await notificationService.SendAsync(notification, token);

            notification.SentDate = DateTimeOffset.UtcNow;
            await notificationRepository.UpdateAsync(notification, token);

        }


        private static string MakeWorkId(NotificationDto notification)
        {
            var hash = notification.IdUser.GetHashCode();
            hash ^= notification.Title.GetHashCode();
            hash ^= notification.Message.GetHashCode();
            return hash.ToString("x");
        }
    }
}