using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using AyaNova.Models;
using AyaNova.Core;
using AyaNova.Util;

namespace AyaNova.Biz
{


    /// <summary>
    /// called by Generator to check for new licenses automatically
    /// 
    /// </summary>
    internal static class CoreJobLicense
    {
        private static ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger("CoreJobLicense");
        private static DateTime _lastCheck = DateTime.MinValue;

#if (DEBUG)
        private static TimeSpan FAST_TRACK = new TimeSpan(0, 1, 0);
        private static TimeSpan SLOW_TRACK = new TimeSpan(0, 5, 0);
#else
        private static TimeSpan FAST_TRACK = new TimeSpan(0, 30, 0);
        private static TimeSpan SLOW_TRACK = new TimeSpan(24, 0, 0);
#endif

        ////////////////////////////////////////////////////////////////////////////////////////////////
        // DoWork
        //
        public static async Task DoWorkAsync()
        {
            log.LogTrace("Job starting");
            var tsSinceLastCheck = DateTime.UtcNow - _lastCheck;
            //which track are we on?
            /*
               NONE = 0,//fast track
                ActiveTrial = 1,//slow track
                ExpiredTrial = 2,//fast track
                ActivePurchased = 3,//slow track
                ExpiredPurchased = 4,//fast track
                Revoked = 5//slow track
            */
            TimeSpan tsCheckFrequency;
            switch (AyaNova.Core.License.ActiveKey.Status)
            {
                case AyaNova.Core.License.AyaNovaLicenseKey.LicenseStatus.NONE:
                case AyaNova.Core.License.AyaNovaLicenseKey.LicenseStatus.ExpiredTrial:
                case AyaNova.Core.License.AyaNovaLicenseKey.LicenseStatus.ExpiredPurchased:
                    tsCheckFrequency = FAST_TRACK;
                    break;
                default:
                    tsCheckFrequency = SLOW_TRACK;
                    break;
            }
            log.LogTrace($"Check frequency{tsCheckFrequency}");
            if (tsSinceLastCheck < tsCheckFrequency)
            {
                log.LogTrace($"Not yet");
                return;
            }

            using (AyContext ct = AyaNova.Util.ServiceProviderProvider.DBContext)
            {
                try//allow exception to bubble up but using try block to ensure the lastcheck is set properly regardless so this doesn't spin out of control
                {
                    var ServerState = (AyaNova.Api.ControllerHelpers.ApiServerState)ServiceProviderProvider.Provider.GetService(typeof(AyaNova.Api.ControllerHelpers.ApiServerState));

                    var ret = await AyaNova.Core.License.FetchKeyAsync(ServerState, ct, log, true);
                    //most often the result will be "notfound" but in future might be other results
                    if (ret == "ok")
                    {
                        //Eventlog
                        await EventLogProcessor.LogEventToDatabaseAsync(new Event(1, 0, AyaType.License, AyaEvent.LicenseFetch, "FromCoreJob"), ct);
                    }
                    if (ret != "notfound")
                    {
                        //I'm thinking do not log internally failed except as debug event as this would fill up log file 
                        //instead if they have a license issue they can do manual fetch and then that will log so they can see error
                        //(also it will return an error to the client)
                        log.LogDebug($"FetchLicense - failed: {ret}");
                    }
                }
                finally
                {
                    _lastCheck = DateTime.UtcNow;
                }
            }
        }
        /////////////////////////////////////////////////////////////////////
    }//eoc
}//eons

