using System.Web.Hosting;
using Hangfire;
using Microsoft.Owin;
using LeafWeb.Web;
using LeafWeb.Web.Services;
using Owin;

[assembly: OwinStartup(typeof(HangfireStartup))]

namespace LeafWeb.Web
{
	public class HangfireStartup
	{
		private const string PiscalProcessQueue = "PiscalProcessQueue";

		public void Configuration(IAppBuilder app)
		{
			//GlobalConfiguration.Configuration
			//	   .UseSqlServerStorage("LeafWebContext");

			app.UseHangfireDashboard();
			app.UseHangfireServer();

			SetupRecurringJobs();
		}

		private void SetupRecurringJobs()
		{
			// TODO: new SqlServerDistributedLock
			RecurringJob.AddOrUpdate<PiscalQueueManager>(PiscalProcessQueue, p => p.ProcessQueue(), Cron.Minutely());
		}

		public static void TriggerPiscalProcessQueue()
		{
			RecurringJob.Trigger(PiscalProcessQueue);
		}
	}

	// http://docs.hangfire.io/en/latest/deployment-to-production/making-aspnet-app-always-running.html
	public class ApplicationPreload : IProcessHostPreloadClient
	{
		public void Preload(string[] parameters)
		{
			HangfireBootstrapper.Instance.Start();
		}
	}

	public class HangfireBootstrapper : IRegisteredObject
	{
		public static readonly HangfireBootstrapper Instance = new HangfireBootstrapper();

		private readonly object _lockObject = new object();
		private bool _started;

		private BackgroundJobServer _backgroundJobServer;

		private HangfireBootstrapper()
		{
		}

		public void Start()
		{
			lock (_lockObject)
			{
				if (_started) return;
				_started = true;

				HostingEnvironment.RegisterObject(this);

				GlobalConfiguration
					.Configuration
					.UseSqlServerStorage("LeafWebContext");
				// Specify other options here

				_backgroundJobServer = new BackgroundJobServer();
			}
		}

		public void Stop()
		{
			lock (_lockObject)
			{
				_backgroundJobServer?.Dispose();

				HostingEnvironment.UnregisterObject(this);
			}
		}

		void IRegisteredObject.Stop(bool immediate)
		{
			Stop();
		}
	}
}