﻿using System;
using System.Threading.Tasks;
using FluentScheduler;
using NLog;

namespace LocalLingua.Web.Infrastructure.Scheduler.Inheritance
{
    internal abstract class BaseJob<T> : IJob where T : class
    {
        protected readonly object Lock;
        protected bool ShuttingDown;
        protected readonly Logger Log = LogManager.GetLogger(nameof(T));
        readonly string _nameOfChild;
        protected BaseJob()
        {
            _nameOfChild = typeof(T).Name;
            Lock = new object();
        }

        protected abstract Task ExecuteAsync();

        void BeforeExecution()
        {
            Log.Info($"Job {_nameOfChild} has started at {DateTime.Now}");
        }

        void AfterExecution()
        {
            Log.Info($"Job {_nameOfChild} has ended at {DateTime.Now}");
        }

        protected void PerformJobWork()
        {
            BeforeExecution();
            ExecuteAsync().Wait();
            AfterExecution();
        }

        public void Execute()
        {
            lock (Lock)
            {
                if (ShuttingDown)
                    return;

                PerformJobWork();
            }
        }

        public virtual void Stop(bool immediate)
        {
            lock (Lock)
            {
                ShuttingDown = true;
            }
        }
    }
}
