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

namespace AyaNova.Biz
{

    /// <summary>
    /// Clean up notification system, keep items down to 90 days
    /// 
    /// </summary>
    internal static class CoreNotificationSweeper
    {
        private static ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger("CoreNotificationSweeper");
        private static DateTime lastSweep = DateTime.MinValue;
        private static TimeSpan DELETE_AFTER_AGE = new TimeSpan(90, 0, 0, 0);
        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.LogTrace("Sweep starting");
            using (AyContext ct = AyaNova.Util.ServiceProviderProvider.DBContext)
            {
                //Notification (App notifications table) - deletes all APP notifications older than 90 days (if they want to keep it then can turn it into a reminder or SAVE it somehow)
                await ct.Database.ExecuteSqlInterpolatedAsync($"delete from anotification where created < {dtDeleteCutoff}");

                //NotifyEvent - deletes any notifyevent with no event date created more than 90 days ago
                await ct.Database.ExecuteSqlInterpolatedAsync($"delete from anotifyevent where eventdate is null and created < {dtDeleteCutoff}");

                //NotifyEvent - If has event date and it's in the past by more than an 8 hours (or whatever sweep interval is, to allow for items about to be delivered momentarily as delivery is on briefer cycle than sweep) 
                //then deletes it if created more than 90 days ago (pretty sure there are no back dated events, once it's passed it's past)
                await ct.Database.ExecuteSqlInterpolatedAsync($"delete from anotifyevent where eventdate < {dtPastEventCutoff} and created < {dtDeleteCutoff}");

                //NotifyDeliveryLog - deletes all log items older than 90 days
                await ct.Database.ExecuteSqlInterpolatedAsync($"delete from anotifydeliverylog where processed < {dtDeleteCutoff}");

            }
            lastSweep = DateTime.UtcNow;
        }



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

    }//eoc


}//eons

