using System.Threading;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using AyaNova.Models;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;

namespace AyaNova.Generator
{

    //Implemented from a example here
    //https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/background-tasks-with-ihostedservice


    /*
    LOOKAT: Generator tasks that should happen:
    - Periodically erase any temp files written to userfiles root (attachments temp files) that are older than a day
        - These files should be normally erased within seconds after uploading and processing into their permanent folder but shit will go wrong
     */

    public class GeneratorService : BackgroundService
    {
        private readonly ILogger<GeneratorService> log;
        // private readonly AyContext ct;
        // private readonly ApiServerState serverState;

        private readonly IServiceProvider provider;

#if(DEBUG)
        private const int GENERATE_SECONDS = 60;
#else
        private const int GENERATE_SECONDS = 60;
#endif

        // public GeneratorService(ILogger<GeneratorService> logger, AyContext dbcontext, ApiServerState apiServerState)
        // {
        //     ct = dbcontext;
        //     log = logger;
        //     serverState = apiServerState;
        // }


        public GeneratorService(ILogger<GeneratorService> logger, IServiceProvider serviceProvider)
        {
            // ct = dbcontext;
            provider = serviceProvider;

            log = logger;
            //  serverState = apiServerState;
        }






        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //don't immediately run the generator stuff on boot
            bool justStarted = true;

            log.LogDebug($"GeneratorService is starting.");

            stoppingToken.Register(() =>
                    log.LogDebug($" GeneratorService background task is stopping."));

            while (!stoppingToken.IsCancellationRequested)
            {

                if (!justStarted)
                {
                    log.LogDebug($"GeneratorService task doing background work.");

                    using (IServiceScope scope = provider.CreateScope())
                    {
                        AyContext ct = scope.ServiceProvider.GetRequiredService<AyContext>();
                        ApiServerState serverState = scope.ServiceProvider.GetRequiredService<ApiServerState>();



                        //=================================================================
                        try
                        {
                            if (!serverState.IsOpen)
                            {
                                log.LogDebug($"GeneratorService: ServerState is closed returning without processing jobs, will try again next iteration");                                
                            }
                            else
                            {
                                await JobsBiz.ProcessJobsAsync(ct, serverState);
                            }
                        }
                        catch (Exception ex)
                        {
                            log.LogError(ex, "Generate::ProcessJobs result in exception error ");

                        }
                        //=================================================================
                    }
                }
                await Task.Delay((GENERATE_SECONDS * 1000), stoppingToken);
                justStarted = false;
            }

            log.LogDebug($"GeneratorService background task is stopping.");

        }

        //originally but kept getting compiler error
        //  public override async Task StopAsync(CancellationToken stoppingToken)
        //         {
        //             log.LogDebug($"GeneratorService StopAsync triggered.");

        //             // Run your graceful clean-up actions
        //         }


        public override Task StopAsync(CancellationToken stoppingToken)
        {
            log.LogDebug($"GeneratorService StopAsync triggered.");
            return Task.FromResult(0);
            // Run your graceful clean-up actions
        }
    }

}