﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace FourInARow.Azure
{
	public abstract class AzureConnector
	{
		// Change here to use a mockup or the real Azure connection.
		static Lazy<AzureConnector> _connector = new Lazy<AzureConnector>(() => new EasyTableAzureConnector());

		public static AzureConnector Instance => _connector.Value;

		protected AzureConnector()
		{
		}

		/// <summary>
		/// Starts a session.
		/// </summary>
		/// <returns>The identifier of the match.</returns>
		public async Task<string> StartSessionAsync(CancellationToken token = default(CancellationToken))
		{
			string id;
			do
			{
				id = GetRandomId();
				if(token.IsCancellationRequested)
				{
					break;
				}
			}
			while (await DoesSessionExistAsync(id, token).ConfigureAwait(false));

			return id;
		}

		/// <summary>
		/// Checks if a given match ID already exists.
		/// </summary>
		/// <returns>The session exist async.</returns>
		/// <param name="sessionId">Identifier.</param>
		public abstract Task<bool> DoesSessionExistAsync(string sessionId, CancellationToken token = default(CancellationToken));

		/// <summary>
		/// Adds a move.
		/// </summary>
		public abstract Task MakeMoveAsync(string sessionId, MoveEntity move, CancellationToken token = default(CancellationToken));

		/// <summary>
		/// Gets a specific move of a match.
		/// </summary>
		public abstract Task<MoveEntity> GetMoveAsync(string sessionId, int moveNumber, CancellationToken token = default(CancellationToken));

		Random _rnd = new Random();

		string GetRandomId() =>	_rnd.Next(10000, 99999).ToString();
	}
}
