using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.Cache;
using AsbCloudDb.Model;

namespace AsbCloudInfrastructure.Services
{
    public class TelemetryAnalyticsBackgroundService : BackgroundService
    {
        private static readonly DbContextOptions<AsbCloudDbContext> options = 
            new DbContextOptionsBuilder<AsbCloudDbContext>()
            .UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True")
            .Options;
        private readonly AsbCloudDbContext context = new AsbCloudDbContext(options);

        private readonly CacheDb cacheDb;
        private readonly ISaubDataCache saubDataCache;

        public TelemetryAnalyticsBackgroundService(ISaubDataCache saubDataCache, CacheDb cacheDb)
        {
            this.saubDataCache = saubDataCache;
            this.cacheDb = cacheDb;
        }

        protected override async Task ExecuteAsync(CancellationToken token = default)
        {
            var telemetryService = new TelemetryService(context, cacheDb);
            var analyticsService = new TelemetryAnalyticsService(context,
                telemetryService, saubDataCache, cacheDb);

            var timeToStartAnalysis = DateTime.Now;

            while (!token.IsCancellationRequested)
            {
                if(DateTime.Now > timeToStartAnalysis)
                {
                    try
                    {
                        timeToStartAnalysis = DateTime.Now.AddHours(1);

                        await Task.Run(() => analyticsService.SaveAnalytics(), token)
                            .ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(ex.Message);
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }

        public override async Task StopAsync(CancellationToken token)
        {
            await base.StopAsync(token).ConfigureAwait(false);
        }

    }
}