using FluentScheduler;
using Valg.EVA.Skanning.ContainerExtensions;
using Valg.EVA.Skanning.BackgroundServices.CheckTransferStatus;
using Valg.EVA.Skanning.BackgroundServices.CleanupAbandonedTransfers;
using Valg.EVA.Skanning.Contracts;
using Valg.EVA.Skanning.Diagnostics;

namespace Valg.EVA.Skanning.BackgroundServices
{
    public class TaskManagerInitializer : ITaskManagerInitializer
    {
        private readonly ITypedFactory typedFactory;
        private readonly IExternalEndpointsConfiguration externalEndpointsConfiguration;

        public TaskManagerInitializer(ITypedFactory typedFactory, IExternalEndpointsConfiguration externalEndpointsConfiguration)
        {
            this.typedFactory = typedFactory;
            this.externalEndpointsConfiguration = externalEndpointsConfiguration;
        }

        public void Initialize()
        {
            JobManager.JobException += TaskManager_UnobservedTaskException;

            var checkTransferStatusService = typedFactory.Create<CheckTransferStatusService>();
            JobManager.AddJob(async () => await checkTransferStatusService.ExecuteAsync().ConfigureAwait(false), s => s.ToRunEvery(externalEndpointsConfiguration.StatusCheckEveryXSeconds).Seconds());

            var abandonedTransfersService = typedFactory.Create<CleanupAbandonedTransfersService>();
            JobManager.AddJob(async () => await abandonedTransfersService.ExecuteAsync().ConfigureAwait(false), s => s.ToRunEvery(1).Minutes());
        }

        private void TaskManager_UnobservedTaskException(JobExceptionInfo exceptionInfo)
        {
            if (exceptionInfo.Exception != null)
            {
                EvaSkanningEventSource.Log.UnhandledExceptionInBackgroundService(exceptionInfo.Name, exceptionInfo.Exception.ToString());
            }
        }
    }
}
