using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Sockeye.Models;

namespace Sockeye.Biz
{

    /// <summary>
    /// Clear out old integration log data
    /// </summary>
    internal static class CoreIntegrationLogSweeper
    {
        private static ILogger log = Sockeye.Util.ApplicationLogging.CreateLogger("CoreIntegrationLogSweeper");
        private static DateTime lastSweep = DateTime.MinValue;
        private static TimeSpan DELETE_AFTER_AGE = new TimeSpan(90, 0, 0, 0);//The same typical 90 days as everything uses
        private static TimeSpan SWEEP_EVERY_INTERVAL = new TimeSpan(8, 0, 0);//once every 8 hours, three times a day

        ////////////////////////////////////////////////////////////////////////////////////////////////
        // DoSweep
        //
        public static async Task DoWorkAsync()
        {
            //This will get triggered roughly every minute, but we don't want to sweep that frequently
            if (DateTime.UtcNow - lastSweep < SWEEP_EVERY_INTERVAL)
                return;
            DateTime dtDeleteCutoff = DateTime.UtcNow - DELETE_AFTER_AGE;
            DateTime dtPastEventCutoff = DateTime.UtcNow - SWEEP_EVERY_INTERVAL;

            log.LogDebug("Sweep starting");
            using (AyContext ct = Sockeye.Util.ServiceProviderProvider.DBContext)
            {                
                await ct.Database.ExecuteSqlInterpolatedAsync($"delete from aintegrationlog where created < {dtDeleteCutoff}");

            }
            lastSweep = DateTime.UtcNow;
        }



        /////////////////////////////////////////////////////////////////////

    }//eoc


}//eons

