using Hotline.Caching.Interfaces;
using Hotline.Realtimes;
using Hotline.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using XF.Domain.Constants;

namespace Hotline.Application.Bigscreen
{
	public class SeatStateDataRefreshService : BackgroundService
	{
		private readonly IServiceScopeFactory _serviceScopeFactory;
		private DateTime _lastModifyTime;

		public SeatStateDataRefreshService(IServiceScopeFactory serviceScopeFactory)
		{
			_serviceScopeFactory = serviceScopeFactory;
			_lastModifyTime = DateTime.Now;
		}

		protected override async Task ExecuteAsync(CancellationToken stoppingToken)
		{
			using var scope = _serviceScopeFactory.CreateScope(); 
			var realtimeService = scope.ServiceProvider.GetRequiredService<IRealtimeService>();
			var logger = scope.ServiceProvider.GetRequiredService<ILogger<SeatStateDataRefreshService>>();
			var systemSettingCacheManager = scope.ServiceProvider.GetRequiredService<ISystemSettingCacheManager>();
			var seatStateDataService = scope.ServiceProvider.GetRequiredService<ISeatStateDataService>();

			try
			{
				int times = int.Parse(systemSettingCacheManager.GetSetting(SettingConstants.BsDataStateChangedTimes)?.SettingValue[0]);

				while (!stoppingToken.IsCancellationRequested)
				{
					await realtimeService.BsSeatStateDataShowChangedAsync1(await seatStateDataService.GetCall24(stoppingToken), stoppingToken);
					await realtimeService.BsSeatStateDataShowChangedAsync2(await seatStateDataService.GetCallTop10(stoppingToken), stoppingToken);
					await realtimeService.BsSeatStateDataShowChangedAsync3(await seatStateDataService.GetCallList(stoppingToken), stoppingToken);
					await realtimeService.BsSeatStateDataShowChangedAsync4(await seatStateDataService.GetCallAverage(stoppingToken), stoppingToken);
					//logger.LogInformation($"send msg: {orders.First().Address}");
					_lastModifyTime = DateTime.Now;
					//}
					await Task.Delay(times, stoppingToken);
				}
			}
			catch (Exception e)
			{
				logger.LogInformation($"send msg: {e.ToString()}");
				throw;
			}
		}
	}
}
