using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.AIHITSyncer.Services;
using PARR.AIHITSyncer.Settings;
using PARR.BLL.Services.Interfaces;
using System.Threading.Tasks;

namespace PARR.AIHITSyncer
{
    internal class AihitSyncer : IAihitSyncer
    {
        private readonly ILogger<AihitSyncer> logger;
        private readonly IMqService mqService;
        private readonly MqSettings mqSettings;
        private readonly IServiceProvider serviceProvider;

        
        public AihitSyncer(
            ILogger<AihitSyncer> logger,
            IMqService mqService,
            MqSettings mqSettings,
            IServiceProvider serviceProvider
            )
        {
            this.logger = logger;
            this.mqService = mqService;
            this.mqSettings = mqSettings;
            this.serviceProvider = serviceProvider;
        }

        public async Task StartAsync()
        {
            logger.LogInformation("Запуск сервиса синхронизации данных из АИХИТ и ПАРР.");
            //var isConnected = mqService.InitConsumer(mqSettings, SyncDataAsync);

            var isConnected = await mqService.InitConsumerAsync(mqSettings, async (string msg) =>
            {
                using (var scope = serviceProvider.CreateScope())
                {
                    var syncerService = scope.ServiceProvider.GetService<ISyncerService>();
                    if (syncerService == null)
                        throw new Exception("Не смог получить сервис ISyncerService, scope.ServiceProvider.GetService<ISyncerService>()");

                    await syncerService.SyncAsync(msg);
                    //await Task.CompletedTask;
                }
            });

            if (!isConnected)
                throw new Exception("Ошибка при подключении к RabbitMq");
        }
        public async Task StopAsync()
        {
           await mqService.DisposeAsync();
        }

    }
}
