using OnlineSalesAutoCrop.CoreAPI.Models;
using OnlineSalesAutoCrop.CoreAPI.Models.Global;
using StackExchange.Redis;
using System;

namespace OnlineSalesAutoCrop.CoreAPI
{
	internal class CacheConnection
	{
		private readonly EnumCacheType cacheType;
		private readonly Lazy<ConnectionMultiplexer> lazyConnection;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="settings"></param>
		/// <exception cref="InvalidOperationException"></exception>
		internal CacheConnection(AppSettings settings)
		{
			try
			{
				cacheType = settings.CacheType;
				if (cacheType == EnumCacheType.Redis && !string.IsNullOrEmpty(settings.CacheUrl))
				{
					lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
					{
						return ConnectionMultiplexer.Connect(settings.CacheUrl);
					});
				}
			}
			catch (Exception e)
			{
				throw new InvalidOperationException(e.Message, e);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		internal ConnectionMultiplexer Connection => lazyConnection?.Value;

		/// <summary>
		/// 
		/// </summary>
		internal EnumCacheType CacheType => cacheType;
	}
}